What's new

How to define custom exception class in Java, Any easiest way?

A

arjunkumar

Newbie
Messages
5
Reaction score
0
Points
35
Sin$
0
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 from here.

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?
 
Operating System
  1. Mac OS
Claws

Claws

Skepta <3
Retired
Lifetime
Journalist Nevar gon' happen in your lifetime Stickied
Messages
7,061
Solutions
1
Reaction score
6,259
Points
3,405
Sin$
-7
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 from here.

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?
That is partially correct. What you'll have to do is implement the following constructor:
Java:
public class MyException extends Exception {
    public MyException(String errorMessage) {
        super(errorMessage);
    }
}

This is because you're trying to instantiate the exception with a string value but you're not implementing any constructor that takes one. What the above does is similar to overriding a method but instead of completely replacing the method, you're just taking the normal imput and passing it up the ladder to the main Exception class so that it does whatever else it needs to do. This is done in this way since constructors can't actually override the super class' constructor like normal methods can.
 
mindarya

mindarya

Newbie
Messages
6
Reaction score
0
Points
35
Sin$
7
That is partially correct. What you'll have to do is implement the following constructor:
Java:
public class MyException extends Exception {
    public MyException(String errorMessage) {
        super(errorMessage);
    }
}

This is because you're trying to instantiate the exception with a string value but you're not implementing any constructor that takes one. What the above does is similar to overriding a method but instead of completely replacing the method, you're just taking the normal imput and passing it up the ladder to the main Exception class so that it does whatever else it needs to do. This is done in this way since constructors can't actually override the super class' constructor like normal methods can.
thanks, i was searching for this info too
 
Top Bottom
Login
Register