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
jeremyyjeremyy 

Custom Exception Classes: Extending Exception

Creating custom exception classes doesn't seem to be documented (well, anyway), and there's some odd behavior when attempting to do so. I'm currently focusing on constructors. Given the following class:

 

 

public class MyException extends Exception{

	private final String exceptionCode;
	
	public MyException(String code) {
		exceptionCode = code;
		// initialization code
	}
}

 

 

The Apex compiler complains with: Save error: System exception constructor already defined: <Constructor>()

 

This class defines a default constructor for the typical reasons: atomic/guaranteed construction, initialization of final variables, etc. Removing the constructor makes the compiler happy. So, are constructors not allowed for classes that extend Exception, or is there some other problem here? 

 

Jeremy

MauricioArdilaMauricioArdila

ok so the problem is the following first

 

you cannot change private final String exceptionCode because its final.

 

On the other hand, you cannot create a constructor with one String cuz it allready exist. 

 

You can try:

 

public Exception(String code, string dummy) 

 {
// do your stuff
 }
I think the best will be to override, but for some reason that does not work. I hope that helps

 

jeremyyjeremyy

exceptionCode is final by design. It must be initialized in a constructor. 

 

This is bizarre, but It appears that any subclass of Exception inherits constructors from Exception. It also seems that these inherited constructors cannot be overridden. 

 

As you pointed out, you could create a new constructor with a signature unique from any of Exception's constructors, but you can't prevent any of the inherited constructors from being used at runtime. Thus, incomplete construction of exception objects.

BritishBoyinDCBritishBoyinDC

Yeah - they remain elusive to me as well - this works, but seems an odd way to have to do it...

 

 

public class My1Exception extends Exception {
    
}


//then in my class
if (x = true)
{
throw new My1Exception('This is my exception, tell me yours');  

}

 

 

MauricioArdilaMauricioArdila

you do not need to do that

 

just called it like this

 

throw new My1Exception('This is my exception, tell me yours');