How to write a custom exception class in Java?

First, it is necessary to create a class that inherits from the Exception class provided by Java or one of its subclasses, such as the RuntimeException class. Then, in this class, you can define a constructor method to initialize the state of the exception object. Finally, you can override some methods of the parent class to achieve specific behaviors of the custom exception class.

Here is an example of a simple custom exception class:

public class MyException extends Exception {
    private int errorCode;
    
    public MyException(int errorCode, String message) {
        super(message);
        this.errorCode = errorCode;
    }
    
    public int getErrorCode() {
        return errorCode;
    }
    
    // 可以重写父类的一些方法,以实现自定义异常类的特定行为
    
    @Override
    public String toString() {
        return "MyException{" +
                "errorCode=" + errorCode +
                ", message='" + getMessage() + '\'' +
                '}';
    }
}

In the example given above, the class MyException inherits from the Exception class and includes an errorCode attribute and a constructor method. The constructor method takes an errorCode and a message parameter to initialize the state of the exception object. This class also overrides the toString() method of the parent class to return a string representation containing the exception information.

By following the steps above, you can create a simple custom exception class. When using it, you can use the throw keyword to throw the exception object, and then use a try-catch statement to catch and handle the exception wherever the method is called.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds