Home >Java >javaTutorial >Can exception classes be customized in Java?

Can exception classes be customized in Java?

王林
王林forward
2020-07-17 16:37:072562browse

Can exception classes be customized in Java?

First of all, exception classes can be customized in Java. So how to customize exception classes in Java?

(Recommended tutorial: java introductory tutorial)

1. First write a class, inherit Exception, or inherit RuntimeException;

2. Provide two There are two constructors, one without parameters and one with String parameters. Just write super(s) in the method body with parameters.

(Video tutorial recommendation: java video tutorial)

Code implementation:

public class Test13 {
    public static void main(String[] args) {
        // 创建自定义异常类的实例,并不抛出
        MyStackOperatorException e = new MyStackOperatorException("栈操作有误");
        String msg = e.getMessage();
        System.out.println(msg);  // 栈操作有误
        e.printStackTrace();  // exception.MyStackOperatorException: 栈操作有误 
        //at exception.Test13.main(Test13.java:23)
}

// 自定义异常类
class MyStackOperatorException extends Exception {
    public MyStackOperatorException() {
    }
    public MyStackOperatorException(String s) {
        super(s);
    }
}

The above is the detailed content of Can exception classes be customized in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete