You need to sign in to do that
Don't have an account?
Steve Chadbourn
How to throw an exception
How do I throw an exception? The developers guide helpfully tells me to use the throw statement and provide it with an exception object but then unhelpfully provides the following example:
throw <exceptionObject>;
I tried:
throw new Exception('error message');
but get the error - type cannot be constructed: Exception.
I did find something that said I could not construct any of the system exceptions so then what excepetion object can I provide to the throw statement?
Figured this one out.
You have to create your own Exception class like this:
public class applicationException extends Exception {}
All Answers
Hi steve,
try {
<code_block>
} catch (<exceptionType>) {
<code_block>
}
// Optional catch statements for other exception types.
// Note that the general exception type, 'Exception',
// must be the last catch block when it is used.
} catch (Exception e) {
<code_block>
throw e;
}
// Optional finally statement
} finally {
<code_block>
}
Thanks but I'm not trying to re-throw an existing exception but throw a brand new one. I want to do something like:
Except I can't as we are not allowed to create a new Exception object.
Figured this one out.
You have to create your own Exception class like this:
public class applicationException extends Exception {}
I used to do this in my code before, but I am not able to do it anymore, perhaps they changed with one of their releases.
MyObj o;
o.addError(); // :( not anymore or I am doing something wrong
Hi kminev,
addError() method can be used in triggers only. Moreover, you can use addError method for only those records that are avaliable in Trigger Context.
Thanks,
Pragati
If you want throw an exception without creating seperate class extensing Exception,then you can use below code:
CalloutException e = new CalloutException();
e.setMessage('This is a constructed exception!');
throw e;
Thanks,
Suraj
We can throw an exception without creating a custom exception class by the following code: Any implicit exception class can be used to throw a suitable exception. Following is the link to more of exception classes:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_exception_methods.htm
Thanks
Sahil
There's a reason Apex more or less forces you to create your own exceptions: custom exceptions actually indicate what is wrong in a strongly-typed way that people calling your code can actually do something with.
Just like you don't declare all your methods to return Object, also don't throw generic exceptions: be specific. It makes your code more readable, maintainable and error-proof.
Don't be the jerk that takes the lazy way out and throws a generic exception, leaving the guy taking over your work to try to understand how the mess you left behind works. Have some pride in your code and think ahead!