Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write custom exception with user defined fields?

This might be an easy thing but I am just confused a bit. How to write a custom exception with user defined fields.

Lets take an example:

public class MyException extends Exception
{
public  MyException()
    {
        super();
    }

    public  MyException(String message)
    {
        super(message);
    }

    public MyException(String message, Throwable cause){
        super(message,cause);
    }
}

Now I want something like:

public MyException(String errCode, String message, Throwable cause){
        //Want to get same result as other constructor but with errCode field   
}

Just confused how to do this. Please help!

like image 865
Helios Avatar asked Mar 21 '14 08:03

Helios


People also ask

How do you create a user defined exception?

In order to create a custom exception, we need to extend the Exception class that belongs to java. lang package. Example: We pass the string to the constructor of the superclass- Exception which is obtained using the “getMessage()” function on the object created.

How do you create a user defined exception in Python?

To generate a user defined exception, we use the “raise” keyword when a certain condition is met. The exception is then handled by the except block of the code. We then use pass statement. pass statement is used to show that we will not implement anything in our custom exception class.

What is custom exception explain it using example?

Creating our own Exception is known as custom exception or user-defined exception. Basically, Java custom exceptions are used to customize the exception according to user need. Consider the example 1 in which InvalidAgeException class extends the Exception class.


1 Answers

public class MyException extends Exception {
    private String errCode;

    public MyException(String errCode, String message, Throwable cause) {
        super(message, cause);
        this.errCode = errCode;
    }

    //getter, setter

}
like image 177
Mustafa Genç Avatar answered Sep 22 '22 09:09

Mustafa Genç