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!
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.
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.
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.
public class MyException extends Exception {
private String errCode;
public MyException(String errCode, String message, Throwable cause) {
super(message, cause);
this.errCode = errCode;
}
//getter, setter
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With