企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# java 中的用户定义的异常 > 原文: [https://beginnersbook.com/2013/04/user-defined-exception-in-java/](https://beginnersbook.com/2013/04/user-defined-exception-in-java/) 在 java 中我们已经定义了异常类,例如`ArithmeticException`,`NullPointerException`等。这些异常已经设置为在预定义条件下触发,例如当你将数字除以零时它会触发`ArithmeticException`,在上一个教程中我们学习了如何抛出这些异常根据您使用[`throw`关键字](https://beginnersbook.com/2013/04/throw-in-java/)的条件明确显示。 在 java 中,我们可以创建自己的异常类,并使用`throw`关键字抛出该异常。这些异常称为**用户定义的**或**自定义**异常。在本教程中,我们将了解如何创建自己的自定义异常并将其抛出到特定条件。 要理解本教程,您应该具备[`try-catch`块](https://beginnersbook.com/2013/04/try-catch-in-java/)和[ java 中的`throw`](https://beginnersbook.com/2013/04/throw-in-java/) 的基本知识。 ## Java 中用户定义的异常示例 ```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 throw throw new MyException("This is My error Message"); } catch(MyException exp){ System.out.println("Catch Block") ; System.out.println(exp) ; } } } ``` **输出:** ```java Starting of try block Catch Block MyException Occurred: This is My error Message ``` **说明:** 你可以看到,在抛出自定义异常时,我在括号中给出了一个字符串(`throw new MyException("This is My error Message");`)。这就是为什么我的自定义异常类中有[参数化构造函数](https://beginnersbook.com/2014/01/parameterized-constructor-in-java-example/)(带有`String`参数)的原因。 **注意:** 1. 用户定义的异常必须扩展`Exception`类。 2. 使用`throw`关键字抛出异常。 ## 自定义异常的另一个例子 在这个例子中,我们从方法中抛出一个异常。在这种情况下,我们应该在方法签名中使用`throws`子句,否则你将得到编译错误,说“方法中未处理的异常”。要了解`throws`子句的工作原理,请参考本指南:[java 中的`throw`关键字](https://beginnersbook.com/2013/04/java-throws/)。 ```java class InvalidProductException extends Exception { public InvalidProductException(String s) { // Call constructor of parent Exception super(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()); } } } ``` **输出:** ```java Caught the exception Product Invalid ```