2. 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.“
WHAT IS A EXCEPTION:-
3. So what kinds of conditions can cause apex to raise, or throw, an
exception? Here are the most common examples:-
1. Your code expects a value from something that is currently null
2.An insert or update statement fails to pass a custom validation rule you
have set.
3.Assigning a query that returns no records or more than one record to a
singleton sobject variable.
4.Accessing a list index that is out of bounds.
CAUSES TO RAISE OR THROW AN EXCEPTION:-
4. 1. When an exception occurs, and you haven't written any code to
deal with it, it's called 'unhandled.' First, an unhandled exception
brings processing to a halt. If the code that has processed so far
contained any database manipulation language (DML) statements,
those statements will be rolled back completely.
2.The system then notifies the running user of the problem. If you
you run into an exception in apex code while using the standard
user interface, a red text message will appear at the top of the
screen showing you the text of the unhandled exception.
WHAT HAPPENS WHEN AN EXCEPTION
OCCURS:-
5. The good news is that apex allows for you 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.
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.
You can have multiple catch blocks to catch any of the 20 different kinds
of exceptions. If you use a generic exception catcher, it must be the last
catch block.
HOW DO I CATCH EXCEPTION:-
6. HERE'S WHAT A TRY-CATCH-FINALLY BLOCK LOOKS
LIKE:-
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 whether there is an exception or not
}
7. HERE'S A TRY-CATCH EXAMPLE FOR AN APEX
CALLOUT:-
try{
HttpResponse res = http.send(req);
} catch(System.CalloutException e){
System.debug('ERROR:' + e);
}
8. HOW DO I HANDLE EXCEPTIONS THAT I'VE CAUGHT:-
1.DML:-
try{
update accounts;
} catch (dmlexception e){
for (account account : accounts) {
account.adderror('there was a problem updating the accounts');
}
} finally {
inprogress = false;
}