Wednesday, 19 September 2012

Throw the Exception in the Class

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."
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

In all these instances we're trying something that the language deems impossible, and an exception is thrown. Apex has 20 different kinds of exceptions--that's a lot of different kinds of exceptions, but since they're all subclassed from a generic exception class they are very similar to deal with. All the exceptions support standard methods for accessing the error message and the exception type.


Throw the Exception in the Class



public class ExceptionHandlingClass{}

try {
    // Your code here 
    
   throw new BaseException('This is Exception Handling');
} catch (Exception e) {  
    // This catches the Exception 
    
}
public class BaseException extends Exception {}

}

No comments:

Post a Comment