Exception Handling In Salesforce 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.

Apex allows to handle your exceptions, and write code to gracefully recover from an error. Apex uses the Try, Catch, Finally construct common to many other programming languages.

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.

Here is an example of what these statements look like and the order in which they should be written:

try {
    // Perform some database operations that 
    //   might cause an exception.
} catch(DmlException e) {
    // DmlException handling code here.
} catch(Exception e) {
    // Generic exception handling code here.
} finally {
    // Perform some clean up.
}