Download as pdf
Download as pdf
You are on page 1of 12
© FOCUSONFORCE Process Automation and Logic: Advanced Topics Implement exception handling in Apex, including custom exceptions as needed CL Penne See eter [@ rocusonronce Table of Contents © wnatare Eacentons © sxceotion Examples @ Heentontianaln @ custombceotions © @ ‘iceotionMethods | rocusonronce After studying this topic, you should be able to: © ‘entity te ctterent types of exceptions in Apex © Determine how toimplement exception handing in Apex © Deserve now to create and useacustom exception oo x |e rocusonronce 2 Introduction This topic describes how to implement exception handling in Apex with examples of bullt-n exceptions. Italso explains how exception Pp ‘methods and custom exceptions can be used in Apex. When an ‘exception is unhandled in Apex it brings code processing to a halt. Exception handling allows developers to try running some cade, catch a potential exception, and run a block of code whether there's an exception or not. This robust framework for exception handling slows recovery from errors and ensures proper functioning of code, Exception Handling in Apex Salesforce provides a comprehensive framework for handling server-side exceptions in the platform. Duct EXCEPTION Brocaioy Ero Nenad caine PNM ail caine cua BuitinExceptions | UsetMVeatch and Use getMessagel)to__addEror0)to abort _Limitxcepton cannot finaysocs obiamerrormesage | “DMLepeatons, Deca Usegecaue) —_Aperepesnesage cistom Exceptions /Usmutbleeial) Ene careanbeuasdto | UseUnitmetods ete of exception display an error ‘or governor lini Gagne) Uitettneimie) — Mesagingisscan Ect thrown eliggenis Yoratuexapton "beusediosend” somanert mens Il inenunoer’”_rorevsemalcamotbe cag Tvowauson UitaeTpeNone—Futuemetodscan ee Toreumpe," bewsedtostore crecepion ——eordea |@ FocusonFoRcE 5| What are Exceptions =a \@ rocusoyronce Exceptions Exceptions are caused by errors encountered when executing code, which disrupt the normal flow of ‘code execution, HANDLED OR UNHANDLED ‘Exceptions can be handled using the exception handling framework, or they can also be unhandled when there sno code to deal with the exception, = BUILT-IN AND CUSTOM Apexincide a frameworktodealwithbulvinexcetionanditieao een possible for developers to create custom exceptions. |@ rocusonronce Exceptions © BUILT-IN EXCEPTIONS. Exceptions can be built-in (e.g. NullPointerException or QueryException) @ CUSTOM EXCEPTIONS Custom exceptions can be created and are designed to be thrown, explicitly @ MULTIPLE EXCEPTION TYPES ‘Apex provides the generic Exception class plus 24 different types of built-in exceptions inthe System namespace, © rocusoyronce Types of Exceptions Below are 1-8 of the 24 specific types of exceptions in the System namespace. ee aad Creel Pier nad Eeaead Problem wth Problemwitnawes —— abiMDPML——peplom hema uch asnchenausoperation —"seviecopraton ment ssaebery ae Uncatchableexception __Problemwith JSON ‘when agovernorlimithas serialization and ‘been exceeded ‘deserlalization Problem with external Invalid method object records parameter problem |@ rocusonronce . Types of Exceptions Below are 9-16 of the 24 specific types of exceptions in the System namespace. Problemitlstssuchas__Problemwth Problem relatedto Tryingtoscessanindex mathematielopeatons authorized acces Preblmthatocars when futettaunds "suthasdvslon bya tocblets Problemvhentyingto _—roblemvath Problemwhen code focmealottomte ——devtrencrea——-PYOBAMWNUESOQL icra featre that has ‘out of bounds null variable re areeeeee not been enabled |@ FocusoNFORCE 1) Types of Exceptions ab Below are 17-24 of the 24 specific types of exceptions in the System namespace. Problem with data Exception Examples \@ oousoyFoRce 2 SOQL Query Causes a QueryException ‘A Queryéxception will be thrown when there is an error encountered involving a query. es esteee esas pes eega aseteas panei eaneeee! (=5] 2/1 wich causes Goeryenception to be throm (ai ervorvillalzobe thrown ifthe query returns no results. So, to avold the error inthis examp! the query must return exactly one record. © rocusonronce 2 QueryException Error Execute Anonymous Error x Line: 3, Column: 1 ‘System. QueryException: List has no rows for assignment to SObject 0K. Null Value Causes a NullPointerException ‘A NullPointerException is thrown when there is an error related to dereferencing a null value of a variable, 2 // The value of @ is null, which causes @ NuliPointerException 2 Integer a; = . 1 aformat operations viedo avarable witha System.debug ("Value of s: ' + 5); essen ee Hsencountered NullPointerException Example of the NullPointerException error. Execute Anonymous Error x Line: 4, Column: 1 ‘System. NullPointerException: Argument cannot be null. 0K |@ rocusonronce « Exception Handling [@ rocusonronce =] Exception Handling Exception handling in Apex can be implemented using try, catch, and finally blocks. These blocks allow code to handle and recover from exceptions. TRY BLOCK CATCH BLOCK FINALLY BLOCK | | HANDLER SYNTAX Code for business logics | | fan exceptions thrown, | |Code in the finally blockis| Syntax run withina try block. itis caught andcode | | run whether an exception ty Inthe catch block has been thrown or not, 7 code have *7 Is executed. andis used for cleanup, | | ? ‘¥en (Exception @) { 7" ese here */ } Finally ¢ /* cote here */ } Exception Handling CAUGHT EXCEPTIONS When exceptions are ‘caught, the default notification mechanisms are not used, MULTIPLE CATCH BLOCKS “Multiple catch blocks can be used tocatch diferent ‘types of exceptions. GENERIC EXCEPTION ‘When the generic Exception is used it must bbe Implemented as the last catch Block. UNCAUGHT EXCEPTIONS ‘When exception handling isnot implemented, the developer and running ser get notified of ‘uncaught exceptions. |e rocusonronce Exception Handling ‘The following illustrates how a finally statement in a try block is always executed regardless of whether ‘an error was encountered or not. £ tapcocager, Sting» Snetetay = new mepcincgee, seh naity [DEBUG ty ater yr cass repre whan ein wa Or |@ rocusonronce Exception Handling ‘The code below shows both catch and finally statements being executed when the try statement ‘encountered an error. “ ee ‘secon SEG |ieoemcray ene a ne ere eee ne oR |e rocusonronce Multiple Catch Blocks The following shows how multiple catch blocks can be used to handle different types of exceptions. suisecistager> aumbere = omy iiatcretepee>{i4 2,335 In this example, the try block will throw aListException error when it Bs cert « tries to access dthelement, which seve sey Ba caver ws comet ten gurtmog 2 epceicn’) | J) ih rat t( since a step catch block snot ‘segs soe semen es ie es gn» defined the generic exception wil Bs sso poi ‘handle the error instead. CaS Se a Ea 1g ae ect es es ne © rocusonronce a Custom Exceptions [@ rocusonronce a Custom Exceptions Custom exceptions can be used to deliberately throw and catch exceptions in methods, ‘CUSTOM HANDLER BEHAVIOR Custom exceptions are capable of specifying detalled error messages and have additional custom error handling in catch blocks. INTERRUPT PROGRAM FLOW Custom exceptions can be used to interrupt the program flow even when asystem exception does not occur. EXTENDS EXCEPTION CLASS Custom exceptions are created by extending the bult-in Exception class. EXPLICITLY THROW EXCEPTION The throw keyword can be used to throw anexception \@ rocusonronce Throwing Custom Exceptions To throw a custom exception, it must be constructed first. There are four ways to construct a ‘custom exception. WITHOUT ARGUMENTS ‘Acustom exception can be instantiated without arguments such as: ryseception ne ne ytscenttonGhs STRING ERROR CHAINED MESSAGE EXCEPTION Astring argument canbe || Anexception froma passedtoitsconstructor | | previous exceptir which willbe used asthe passed error message: tyexception ww = pew exception me = new ryercentioned; STRING AND EXCEPTION Astring error message anda chained exception i passed: vtecention oopst"y el: © rocusoyronce Custom Exception Example The following shows a custom exception class called CustomException where an instance is being thrown in a sample try-catch block if @ certain condition is met, [/oetinition of Custom Excoption public class Customesception evvends Exception() ‘/eustentxception Manéling using try, throw and catch seve EO (a> 300 ) throw new CustanException(); + eaten ( Gstonteeption ©) ( > |e rocusonronce Thename ofa custom ‘exception class must end Exception Methods (@ rocusoyFonce Exception Methods in and custom exceptions have common methods. EXCEPTION DETAILS. Exception methods may be used to obtain more Information about the exception, MESSAGE AND TYPE Exception methods canbe used toreturn the error message and exception type. ERROR MESSAGE EY For example, getMessage method can be used to obtain the error message tobe displayed to the user. |@ rocusonronce Exception Methods ERROR CAUSE The getCause methad returns the cause of the exception asan exception object. LINE NUMBER ESA The getLineNumber method returns the line numberof the exception ERROR TYPE, aD The get TypeName method returns the type of exception. OTHER METHODS BY other than common methods, DMLExceptions and EmallExceptions have additional methods such as getDmlFleldNames and getDmiMessage. |@ rocusonronce Exception Methods ‘The following illustrates the different types of information that can be retrieved using the common methods available in an Exception instance. ove RSME mpuncineer¢ | rocusonronce Handling Catchable Exceptions Ea Below are some actions to consider when handling caught exceptions. PREVENTDML | DISPLAY ERROR EMAILERROR STORE ERROR OPERATION MESSAGE MESSAGES MESSAGES ‘The addrror()method | | The ApexPagesmessage | Errormessages canbe || Error detalls can be canbecalled onarecord || classcanbeusedto || senttoadevelopervia || —storedinacustom orfieldtoprevent DML || showerrorsrelatedto femal using the object usinga ‘operations from exceptions caused bya Messaging lass. future method committing. custom controller or controller extension for 2 Visualforce page, Eg |@ rocusonronce a Handling Uncatchable Exceptions There are exceptions that require the termination of code execution and do not allow code to resume Via exception handling LIMIT EXCEPTIONS. Exceeding governor limits halts processing of code and causes LimitException which cannot be caught using exception handling. USE LIMIT METHODS Limit methods such as LimitsgetOMLRows) and Limits getLinitOMLRows|) can be used to jbtain information regarding governor limits, ‘ASSERT EXCEPTIONS Exceptions thrown due to the failure of assertion statements suchas ystemassertEquale) or AssertareEqual cannot be caught. | rocusonronce a Learn More © wceotion Class and Buln xcentions ceate Custom rcentions e Cp fulltinExcentions and Common Methods © Lrcentlonsin Avex |@ rocusontonce a

You might also like