Home >Java >javaTutorial >How to customize exceptions in Java?
Creating custom exceptions in Java can improve application robustness. It requires: Create a custom exception class, inheriting from Exception or RuntimeException. Throws a custom exception, similar to throwing a regular exception. Catch custom exceptions when calling methods for more informative error messages.
Tutorial on Custom Exceptions in Java
In Java, custom exceptions can help you provide more specific and meaningful error messages, thereby improving application robustness.
Create a custom exception class
The custom exception class needs to inherit Exception
or RuntimeException
:
public class MyCustomException extends Exception { private String message; public MyCustomException(String message) { super(message); this.message = message; } public String getMessage() { return message; } }
Throwing a custom exception
Throwing a custom exception is similar to throwing a regular exception:
throw new MyCustomException("自定义错误消息");
Practical case
Consider a class called Calculator
that has a divide()
method to calculate the quotient of two numbers:
public class Calculator { public double divide(int numerator, int denominator) throws MyCustomException { if (denominator == 0) { throw new MyCustomException("除数不能为零"); } return (double) numerator / denominator; } }
Use custom Exceptions
To use a custom exception, catch it when calling the divide()
method:
try { double result = calculator.divide(10, 2); System.out.println(result); } catch (MyCustomException e) { System.out.println(e.getMessage()); // 打印 "除数不能为零" }
Conclusion
With custom exceptions, you can provide more informative and targeted error handling in your Java applications. This increases the robustness of the application and improves the user experience.
The above is the detailed content of How to customize exceptions in Java?. For more information, please follow other related articles on the PHP Chinese website!