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

Can exception classes be customized in Java?

王林
Release: 2020-07-17 16:37:07
forward
2565 people have browsed it

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);
    }
}
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template