Java如何创建自定义异常类?
您可以为自己的应用程序特定目的定义自己的异常类。通过扩展java.lang.Exception用于检查的异常或未检查的异常的类来创建异常类java.lang.RuntimeException。通过创建自己的Exception类,您可以更精确地确定问题。
package org.nhooo.example.fundamental; public class CustomExceptionExample { public static void main(String[] args) { int x = 1, y = 0; try { int z = CustomExceptionExample.divide(x, y); System.out.println("z = " + z); } catch (DivideByZeroException e) { e.printStackTrace(); } } public static int divide(int x, int y) throws DivideByZeroException { try { return (x / y); } catch (ArithmeticException e) { String m = x + " / " + y + ", trying to divide by zero"; throw new DivideByZeroException(m, e); } } }
class DivideByZeroException extends Exception { DivideByZeroException() { } DivideByZeroException(String message) { super(message); } DivideByZeroException(String message, Throwable cause) { super(message, cause); } }