Exception Handling In Apex Classes
An exception is a special condition that changes the normal flow of program execution. That is, it's when something bad happens that the program can't deal with during execution. Exceptions are the language's way of throwing up its hands and saying, I can't deal with this, you need to handle those exceptions. we have three methods to catch this exceptions.
- Try: If an exception occurs within the try block, that exception is handled by an exception handler associated with it. To associate an exception handler with a try block, you must put a catch block after it
- Catch: Each catch block is an exception handler that handles the type of exception indicated by its argument. The argument type, ExceptionType , declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class. The handler can refer to the exception with name
- Finally: This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling it allows the programmer to avoid having cleanup code accidentally bypassed by a return , continue , or break.
Simply You "try" to run your code. If there is an exception, you "catch" it and can run some code, then you can "finally" run some code whether you had an exception or not.
Syntax:
try{ //Your code here } catch (ListException e) { //Optional catch of a specific exception type //Specific exception handling code here } catch (Exception e) { //Generic exception handling code here } finally { //optional finally block //code to run whether there is an exception or not }