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?
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:In response to the question below about not calling
super()
in the defualt constructor, Oracle has this to say:If you inherit from Exception, you have to provide a constructor that takes a String as a parameter (it will contain the error message).
A typical custom exception I'd define is something like this:
I even create a template using Eclipse so I don't have to write all the stuff over and over again.
Reason for this is explained in the Inheritance article of the Java Platform which says:
Exception class has two constructors
public Exception()
-- This constructs an Exception without any additional information.Nature of the exception is typically inferred from the class name.public Exception(String s)
-- Constructs an exception with specified error message.A detail message is a String that describes the error condition for this particular exception.