0

In Apex I have this:

...
if (forceException) {
   Integer a = 1/0;
}
...

But after I ran SFDX Scanner I got an error that variable a is defined but not used (UnusedLocalVariable) so I decided to do next thing:

...
if (forceException) {
   throw new Exception('Exception');
}
...

but now I had problem because pipeline throw me next error:

Type cannot be constructed: Exception

does anyone know is there any other option what I can use in if statement instead of throw new Exception('Exception'); and Integer a = 1/0;?

3 Answers 3

-1

You can create a custom Exception class, and throw an instance of that. For example:

class MyOwnException extends Exception{}

and then you can throw the custom exception.

if (forceException) {
   throw new MyOwnException('Exception');
}
1

For constructing user-defined custom exceptions as well as standard exceptions from your Apex class, you must extend the built-in Exception class and make sure your class (or child class) name ends with the word Exception. For instance, MyException or MyCustomException.

Here is an example of creating custom exceptions from the Apex Developer Guide.

public class ExceptionExample {
public virtual class BaseException extends Exception {}
public class OtherException extends BaseException {}

public static void testExtendedException() {
    try {
        Integer i=0;
        // Your code here
        if (i < 5) throw new OtherException('This is bad');
    } catch (BaseException e) {  
        // This catches the OtherException
        System.debug(e.getMessage());
    }  
  }
}

In the above example, we are using a virtual class (like Java) that extends built-in Salesforce's Exception and using it as a base class for inheriting all common Exception methods. By following the same approach, you could throw user-defined custom exceptions.

Also, please refer Exception Class and Built-In Exceptions for more information.

1
  • 1
    You can also construct many of the standard exceptions, too.
    – sfdcfox
    Commented Aug 3, 2021 at 14:12
0

You can throw other Exceptions like AuraHandledException(''); or NullPointerException();

1
  • In this case I get next error: Method does not exist or incorrect signature: void NullPointerException() from the type NamesOfMyClasses
    – mhdev
    Commented Aug 3, 2021 at 13:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .