Home  >  Article  >  Java  >  Cases about custom exception classes in Java

Cases about custom exception classes in Java

黄舟
黄舟Original
2017-09-26 10:04:041865browse

This article mainly introduces relevant information about detailed examples of Java custom exception classes. I hope this article can help everyone learn and understand this part of the content. Friends in need can refer to it

Detailed explanation of examples of Java custom exception classes

Why should you write your own exception class? If there is no exception provided in jdk, we have to write it ourselves. Our commonly used classes ArithmeticException, NullPointerException, NegativeArraySizeException, ArrayIndexoutofBoundsException, and SecurityException all continue the parent class RuntimeException, and this parent class also has a parent class called Exception. Then when we write our own exception class, we also continue the Exception class.

Practice:


class MyException extends Exception { //继续了Exception这个父类
private int detail;
MyException(int a) {
detail = a;}
public String toString() {
return "MyException[" + detail + "]";
}}
class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("调用 compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("常规退出 ");
}
public static void main(String args[]) {
try {
compute(1);
compute(20);
} catch (MyException e) {
System.out.println("捕捉 " + e); //这样就可以用自己定义的类来捕捉异常了
}}}

The above is the detailed content of Cases about custom exception classes in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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