How to define custom exception class in Java, the easiest way?
Solution 1
No, you don't "inherit" non-default constructors, you need to define the one taking a String in your class. Typically you use super(message)
in your constructor to invoke your parent constructor. For example, like this:
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
Solution 2
A typical custom exception I'd define is something like this:
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
public CustomException(String message, Throwable throwable) {
super(message, throwable);
}
}
I even create a template using Eclipse so I don't have to write all the stuff over and over again.
Solution 3
If you use the new class dialog in Eclipse you can just set the Superclass field to java.lang.Exception
and check "Constructors from superclass" and it will generate the following:
package com.example.exception;
public class MyException extends Exception {
public MyException() {
// TODO Auto-generated constructor stub
}
public MyException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public MyException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
public MyException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
}
In response to the question below about not calling super()
in the defualt constructor, Oracle has this to say:
Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass.
Solution 4
Reason for this is explained in the Inheritance article of the Java Platform which says:
"A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass."
Solution 5
package customExceptions;
public class MyException extends Exception{
public MyException(String exc)
{
super(exc);
}
public String getMessage()
{
return super.getMessage();
}
}
import customExceptions.MyException;
public class UseCustomException {
MyException newExc=new MyException("This is a custom exception");
public UseCustomException() throws MyException
{
System.out.println("Hello Back Again with custom exception");
throw newExc;
}
public static void main(String args[])
{
try
{
UseCustomException use=new UseCustomException();
}
catch(MyException myEx)
{
System.out.println("This is my custom exception:" + myEx.getMessage());
}
}
}
Related videos on Youtube
yegor256
Lab director at Huawei, co-founder at Zerocracy, blogger at yegor256.com, author of Elegant Objects book; architect of Zold.
Updated on December 31, 2020Comments
-
yegor256 over 3 years
I'm trying to define my own exception class the easiest way, and this is what I'm getting:
public class MyException extends Exception {} public class Foo { public bar() throws MyException { throw new MyException("try again please"); } }
This is what Java compiler says:
cannot find symbol: constructor MyException(java.lang.String)
I had a feeling that this constructor has to be inherited from
java.lang.Exception
, isn't it? -
vulkanino over 13 yearsthe default constructor IS inherited.
-
jmj over 13 yearsI think you should add reason also.
-
Michael Borgwardt over 13 years@vulkanino: No. The default constructor is added by the compiler for every class that defines no constructor of its own. If you define an explicit constructor, you don't get the default even if the superclass has it, and if your class has no constructor, you get the default even if the superclass does not have it.
-
Stephen C over 13 yearsactually, that is incorrect. If your code uses a constructor with one String argument, then you have to declare it. However, an Exception subclass can be defined with no explicit constructors ... because Exception has a no-args constructor.
-
Sean Patrick Floyd over 13 years
if your class has no constructor, you get the default even if the superclass does not have it
The last part is impossible, unless the superclass has a default constructor that is accessible to this class (may be protected or package-protected). Otherwise you must explicitly call one of the parent constructors, or compilation will fail. -
user1876508 over 10 yearswhat would this return?
-
Danilo Piazzalunga over 10 yearsActually, since Java 1.4, there are two more constructors:
public Exception(Throwable)
andpublic Exception(String, Throwable)
. They are needed to properly support exceptions chaining. -
Danilo Piazzalunga over 10 yearsPlease add the
MyException(Throwable)
andMyException(String, Throwable)
constructors to properly support exceptions chaining. -
jeremyjjbrown over 10 yearsYou can just extend Exception when creating your Class in Eclipse and you'll get all four constructors. You don't need a template.
-
KNU almost 10 years@DaniloPiazzalunga agree with you . source : Constructor Summary docs.oracle.com/javase/1.5.0/docs/api/java/lang/Exception.html
-
ThePerson almost 10 yearsIt would just print out "Hello Back Again with custom exception" which is from the constructor for UseCusomException, the exception would be thrown then caught in the main which would print out "This is my custom exception:This is a custom exception".
-
ceving over 9 yearsWhy is it not necessary for the default constructor to call
super()
? -
Kevin Brey over 9 years
-
byxor over 7 yearsNearly 3 years later and none of the extra constructors have been added. :(
-
djna over 7 years@Brandon Ibbotson anyone who cares to do so is free to add them; in my view they are not germane to the original question, but I have no objections to anyone editing my answer.
-
byxor over 7 years@djna I agree, plus they're implicitly added anyway so it wouldn't make any difference.
-
halil over 7 years@BrandonIbbotson What do you mean by 'they', and where are they added? If what you meant by 'they' are superclass constructors and by 'where' is subclass, then you are wrong. Superclass constructors are not implicitly added to subclass. Plus I can't see any other subject in the previous sentences for those words to refer.
-
byxor over 7 years@halil That is definitely not what I meant. I admit that my comment could have made you think that way. By "implicitly added" I just meant that you can invoke the
Exception
constructors as if they were already added to theMyException
class, even ifMyException
has not overridden them. -
rooni over 5 yearswhy do you say "non-default" c'tor?
-
ZhaoGang over 4 yearsWhen should we use the second Consutructor instead of the first one?