原文: https://beginnersbook.com/2013/04/user-defined-exception-in-java/
在 java 中我们已经定义了异常类,例如ArithmeticException,NullPointerException等。这些异常已经设置为在预定义条件下触发,例如当你将数字除以零时它会触发ArithmeticException,在上一个教程中我们学习了如何抛出这些异常根据您使用throw关键字的条件明确显示。
在 java 中,我们可以创建自己的异常类,并使用throw关键字抛出该异常。这些异常称为用户定义的或自定义异常。在本教程中,我们将了解如何创建自己的自定义异常并将其抛出到特定条件。
要理解本教程,您应该具备try-catch块和 java 中的throw 的基本知识。
Java 中用户定义的异常示例
/* This is my Exception class, I have named it MyException* you can give any name, just remember that it should* extend Exception class*/class MyException extends Exception{String str1;/* Constructor of custom exception class* here I am copying the message that we are passing while* throwing the exception to a string and then displaying* that string along with the message.*/MyException(String str2) {str1=str2;}public String toString(){return ("MyException Occurred: "+str1) ;}}class Example1{public static void main(String args[]){try{System.out.println("Starting of try block");// I'm throwing the custom exception using throwthrow new MyException("This is My error Message");}catch(MyException exp){System.out.println("Catch Block") ;System.out.println(exp) ;}}}
输出:
Starting of try blockCatch BlockMyException Occurred: This is My error Message
说明:
你可以看到,在抛出自定义异常时,我在括号中给出了一个字符串(throw new MyException("This is My error Message");)。这就是为什么我的自定义异常类中有参数化构造函数(带有String参数)的原因。
注意:
- 用户定义的异常必须扩展
Exception类。 - 使用
throw关键字抛出异常。
自定义异常的另一个例子
在这个例子中,我们从方法中抛出一个异常。在这种情况下,我们应该在方法签名中使用throws子句,否则你将得到编译错误,说“方法中未处理的异常”。要了解throws子句的工作原理,请参考本指南:java 中的throw关键字。
class InvalidProductException extends Exception{public InvalidProductException(String s){// Call constructor of parent Exceptionsuper(s);}}public class Example1{void productCheck(int weight) throws InvalidProductException{if(weight<100){throw new InvalidProductException("Product Invalid");}}public static void main(String args[]){Example1 obj = new Example1();try{obj.productCheck(60);}catch (InvalidProductException ex){System.out.println("Caught the exception");System.out.println(ex.getMessage());}}}
输出:
Caught the exceptionProduct Invalid
