+ Start a Discussion
Steve ChadbournSteve 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?
Best Answer chosen by Admin (Salesforce Developers) 
Steve ChadbournSteve Chadbourn

Figured this one out.

You have to create your own Exception class like this:

public class applicationException extends Exception {}

Then you can throw that:
 
throw new applicationException(You can't do that here');

All Answers

dotnet developedotnet develope

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>

 

}

 

T&R
:smileyhappy:
Steve ChadbournSteve Chadbourn

Thanks but I'm not trying to re-throw an existing exception but throw a brand new one. I want to do something like:

Code:
if (myValue < 6)
{
  // some code
}
else
{
   throw new Exception('Invalid myValue');
}


 Except I can't as we are not allowed to create a new Exception object.

Steve ChadbournSteve Chadbourn

Figured this one out.

You have to create your own Exception class like this:

public class applicationException extends Exception {}

Then you can throw that:
 
throw new applicationException(You can't do that here');
This was selected as the best answer
EdLEdL
Not 100% sure, but can't you just do
 
Code:
object_name a = //define object

a.addErrors('My error Here');

 
kminevkminev

 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

Force.comForce.com

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

 

try{
     upsert accs;
} 
catch (DMLException e){
  for (Account acc : accs){ 
    Account a = Trigger.oldMap.get(a.Id); 		        
    a.adderror('There is a problem while upserting records');        		                                                  	                      
  }
}

 

Thanks,

Pragati

Jhon Cortes GasparJhon Cortes Gaspar
Hi Steve, Its late but here is the solution without creating new custom Exception.You could use standard Exception class as following:
 
throw new Exceptions.SystemException('Your Message');

 
Suraj MakandarSuraj Makandar
Hi All,

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
Sahil Sharma 36Sahil Sharma 36
Hey Everyone,

We can throw an exception without creating a custom exception class by the following code:
throw new IllegalArgumentException('Any exception related text');
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
Frans Flippo 20Frans Flippo 20
All of the answers recommending to appropriate and abuse existing exceptions like CalloutException and IllegalArgumentException: DON'T DO THAT!

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!