Java异常显式转换与隐式转换

huangapple go评论67阅读模式
英文:

Java exception explicit casting vs implicit casting

问题

Came across this piece of code: -

public T call(final Callable 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. 为什么在第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&#39;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&#39;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&#39;t enforce the exception to be declared on the method with a `throws`. Line 8 wrapes the checked exception into a unchecked exception.

</details>



huangapple
  • 本文由 发表于 2020年10月11日 04:45:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/64298130.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定