Exceptional Handling -try, catch, finally, throw keywords
An exception occurs during the execution of a program. We have to handle the excretion in code. Like Java, Apex has an exception handling mechanism. Below are the Keywords(try, catch, finally, throw keywords) related to Exceptional Handling
try
try keyword is used to surround a block of code in which an exception can occur.
Example
try {
// Your code here
} catch (ListException e) {
// List Exception handling code
// here
}
catch
catch keyword is used to handle a particular type of exception.
In the following example, the catch block specifically handles ListException and no other type of exception.
try {
// Your code here
} catch (ListException e) {
// List Exception handling code here
}
finally
This keyword is used to identifies a block of code that is guaranteed to execute.
Example
try {
// Your code here
} catch (ListException e) {
// List Exception handling code
} finally {
// will execute with or without exception
}
throw
throw keyword is used to explicitly throw an exception, signaling that an error has occurred.
In the following example, we are explicitly throwing an exception MyException
for some condition.
public class MyException extends Exception {}
public class MyPO implements PO {
public void doWork() {
try {
Integer i;
if (i < 5)
throw new MyException();
} catch (MyException e) {
// Your MyException handling
// code here
}
}
}