[英]Unhandled exception error not showing for a function
I want to restrict my function divide
to always be called from a try block.我想限制我的 function
divide
总是从 try 块中调用。 But when the function is called from main
, without using try block, it does not show "Unhandled Exception" error?但是当从
main
调用 function 时,不使用 try 块,它不会显示“未处理的异常”错误?
class Main {
public static void main(String[] args) {
System.out.println(Main.divide(5.0f, 2.0f));
System.out.println(divide(5.0f, 2.0f));
}
static float divide(float x, float y) throws ArithmeticException {
if (y == 0)
throw new ArithmeticException("Cannot divide by 0!");
else
return x/y;
}
}
Output: Output:
2.5
2.5
To make use of "throws" keyword to throw the checked exception, you can force the calling method to handle the exception.要使用“throws”关键字抛出检查异常,可以强制调用方法处理异常。
Make this change:进行此更改:
From:从:
static float divide(float x, float y) throws ArithmeticException {
To:到:
// Custom checked exception
static class UserDefinedException extends Exception {
public UserDefinedException(String str) {
super(str);
}
}
// Good approach
static float divide(float x, float y) throws UserDefinedException {
if (y == 0)
throw new UserDefinedException("Cannot divide by 0!");
else
return x/y;
}
// Bad approach
//static float divide(float x, float y) throws Exception { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.