function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
lvivaninlvivanin 

User defined Exception in apex class

How can we throw exception in Apex. I am trying do something like:

 

 

 

 

public class testExpt
{
public void exptTesting(Test_Object__c[] testObjectArray)
{
for (Test_Object__c t: testObjectArray)
{
if(t.test_field__c < 25.00)
{
throw new Exception('This is bad number');
}
}
}
}

 

 

 How can I achieve this in Apex?

 

Best Answer chosen by Admin (Salesforce Developers) 
IanRIanR

Hi,

 

Create a trivial class that extends Exception,

 

e.g.

 

 
public class GeneralException extends Exception

{

}

 

 

then in your code, you can use:

 

 

throw new GeneralException('This is bad number');

 

 

 

HTH, Ian :)

 

All Answers

IanRIanR

Hi,

 

Create a trivial class that extends Exception,

 

e.g.

 

 
public class GeneralException extends Exception

{

}

 

 

then in your code, you can use:

 

 

throw new GeneralException('This is bad number');

 

 

 

HTH, Ian :)

 

This was selected as the best answer
lvivaninlvivanin
Thank you IanR! - i am able to do so with your help.