英文:
Java exception explicit casting vs implicit casting
问题
Came across this piece of code: -
public
try {
return callable.call();
} catch (Exception exception) {
if (exception instanceof RuntimeException) {
throw (RuntimeException) exception; // Line 6
} else {
throw new RuntimeException(exception); // Line 8
}
}
}
1. 为什么在第6行要执行 `(RuntimeException) exception` 操作?
2. 第6行和第8行抛出的异常有什么区别?它们不是在做相同的事情吗?
<details>
<summary>英文:</summary>
Came across this piece of code: -
public <T> T call(final Callable<T> callable) {
try {
return callable.call();
} catch (Exception exception) {
if (exception instanceof RuntimeException) {
throw (RuntimeException) exception; // Line 6
} else {
throw new RuntimeException(exception); // Line 8
}
}
}
1. What is the need for doing a `(RuntimeException) exception` at line 6?
2. What is the difference between the exceptions being thrown at line 6 v/s line 8. Aren't they doing the same thing?
</details>
# 答案1
**得分**: 1
代码的目的是将一个已检查的异常转换为未检查的异常。在Java中,已检查的异常必须在使用`throws`关键字的方法中声明,而未检查的异常则不需要在方法上声明。`Exception`是所有异常的基类,而`RuntimeException`(它是`Exception`的子类)是所有未检查异常的基类。
第6行的代码是为了让编译器满意。由于`Exception`是一个已检查的异常,在将其强制转换为`RuntimeException`时,编译器不会强制在方法上声明该异常。第8行将已检查的异常包装成了一个未检查的异常。
<details>
<summary>英文:</summary>
The code there is to transform a checked exception into a unchecked exception. In Java, checked exceptions have to be declared on a method with the `throws` keyword, while unchecked exceptions don't need to be declared on the method. `Exception` is the base class for all exceptions while `RuntimeException` (which is a subclass of `Exception`) is the base class for all unchecked exceptions.
The code on line 6 is to make the compiler happy. As `Exception` is a checked exception, by casting it to `RuntimeException` the compiler won't enforce the exception to be declared on the method with a `throws`. Line 8 wrapes the checked exception into a unchecked exception.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论