Exception Handling in Apex


Exception Handling:
  • Exception handling refers to the way that a program handles exceptional circumstances.
Try-Catch-Finally Statements:
  • The try statement identifies a block of code in which an exception can occur.
  • The catch statement identifies a block of code that can handle a particular type of exception. A single try statement can have zero or more associated catch statements. Each catch statement must have a unique exception type. Also, once a particular exception type is caught in one catch block, the remaining catch blocks, if any, aren’t executed.
  • The finally statement identifies a block of code that is guaranteed to execute and allows you to clean up your code. A single try statement can have up to one associated finally statement. Code in the finally block always executes regardless of whether an exception was thrown or the type of exception that was thrown. Because the finally block always executes, use it for cleanup code, such as for freeing up resources.

Example: