Java 尝试/捕获与抛出异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3241571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
try/catch versus throws Exception
提问by carlos
Are these code statements equivalent? Is there any difference between them?
这些代码语句是否等效?它们之间有什么区别吗?
private void calculateArea() throws Exception {
....do something
}
private void calculateArea() {
try {
....do something
} catch (Exception e) {
showException(e);
}
}
回答by Jon Skeet
Yes, there's a huge difference - the latter swallows the exception (showing it, admittedly), whereas the first one will let it propagate. (I'm assuming that showException
doesn't rethrow it.)
是的,有一个巨大的区别 - 后者吞下了异常(无可否认地显示它),而第一个将让它传播。(我假设这showException
不会重新抛出它。)
So if you call the first method and "do something" fails, then the caller will have to handle the exception. If you call the second method and "do something" fails, then the caller won't see an exception at all... which is generally a bad thing, unless showException
has genuinelyhandled the exception, fixed whatever was wrong, and generally made sure that calculateArea
has achieved its purpose.
所以如果你调用第一个方法并且“做某事”失败,那么调用者将不得不处理异常。如果调用第二种方法和“做什么”失败,则调用者不会看到在所有的例外......通常是一件坏事,除非showException
有真正处理的异常,无论固定错了,一般做肯定这样calculateArea
就达到了目的。
You'll be able to tell this, because you can't call the first method without eithercatching Exception
yourself ordeclaring that your method might throw it too.
您可以讲这个,因为你不能调用的第一个方法没有任何追赶Exception
自己或者宣告你的方法可能把它太。
回答by Lyle
Yes. The version which declares throws Exception
will require the calling code to handle the exception, while the version which explicitly handles it will not.
是的。声明的版本throws Exception
将需要调用代码来处理异常,而显式处理它的版本则不需要。
i.e., simply:
即,简单地说:
performCalculation();
vs. moving the burden of handling the exception to the caller:
与将处理异常的负担转移给调用者:
try {
performCalculation();
catch (Exception e) {
// handle exception
}
回答by samitgaur
First one throws Exception
, so the caller needs to handle the Exception
. Second one catches and handles Exception
internally, so the caller doesn't have to do any exception handling.
第一个throws Exception
,所以调用者需要处理Exception
. 第二个在Exception
内部捕获和处理,因此调用者不必进行任何异常处理。
回答by Chris Thompson
Yes, there is a great deal of difference between them. The in the first code block, you pass the exception to the calling code. In the second code block you handle it yourself. Which method is correct depends entirely on what you are doing. In some instances, you want your code to handle the exception (if a file isn't found and you want to create it, for instance) but in others, you want the calling code to handle the exception (a file isn't found and they need to specify a new one or create it).
是的,它们之间有很大的不同。在第一个代码块中,您将异常传递给调用代码。在第二个代码块中,您自己处理。哪种方法正确完全取决于你在做什么。在某些情况下,您希望代码处理异常(例如,如果找不到文件而您想创建它),但在其他情况下,您希望调用代码处理异常(未找到文件)并且他们需要指定一个新的或创建它)。
Generally speaking as well, you don't want to catch a generic exception. Instead, you'll want to catch only specific ones, such as FileNotFoundException
or IOException
because they can mean different things.
一般来说,您也不希望捕获通用异常。相反,您只想捕获特定的,例如FileNotFoundException
或IOException
因为它们可能意味着不同的事情。
回答by Eyal Schneider
I assume that by "identical" you are referring to behavior.
我认为“相同”是指行为。
A behavior of a function can be determined by:
函数的行为可以通过以下方式确定:
1) Returned value
1) 返回值
2) Thrown exceptions
2) 抛出异常
3) Side effects (i.e changes in the heap, file system etc)
3) 副作用(即堆、文件系统等的变化)
In this case, the first method propagates any exception, while the second throws no checked exception, and swallows most of the unchecked exceptions as well, so the behavior IS different.
在这种情况下,第一个方法传播任何异常,而第二个方法不抛出任何已检查的异常,并吞下大部分未检查的异常,因此行为不同。
However, if you guarantee that "do something" never throws an exception, then the behavior would be identical (though the compiler will require the caller to handle the exception, in the first version)
但是,如果你保证“做某事”永远不会抛出异常,那么行为将是相同的(尽管在第一个版本中编译器会要求调用者处理异常)
--edit--
- 编辑 -
From the point of view of API design, the methods are completely different in their contract. Also, throwing class Exception is not recommended. Try throwing something more specific to allow the caller to handle the exception better.
从 API 设计的角度来看,这些方法的契约完全不同。此外,不建议抛出类异常。尝试抛出更具体的东西,让调用者更好地处理异常。
回答by Arjun Thakur
There is one particular scenario where we cannot use throws, we have got to use try-catch. There is a rule "An overridden method cannot throw any extra exception other than what its parent class is throwing". If there is any extra exception that should be handled using try-catch. Consider this code snippet. There is a simple base class
有一种特殊情况,我们不能使用 throws,我们必须使用 try-catch。有一条规则“被覆盖的方法不能抛出除其父类抛出的异常之外的任何额外异常”。如果有任何额外的异常应该使用 try-catch 处理。考虑这个代码片段。有一个简单的基类
package trycatchvsthrows;
public class Base {
public void show()
{
System.out.println("hello from base");
}
}
and it's derived class:
它是派生类:
package trycatchvsthrows;
public class Derived extends Base {
@Override
public void show() {
// TODO Auto-generated method stub
super.show();
Thread thread= new Thread();
thread.start();
try {
thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// thread.sleep(10);
// here we can not use public void show() throws InterruptedException
// not allowed
}
}
When we have to call thread.sleep() we are forced to use try-catch, here we can not use:
当我们不得不调用thread.sleep()时,我们被迫使用try-catch,这里我们不能使用:
public void show() throws InterruptedException
because overridden method can not throw extra exceptions.
因为被覆盖的方法不能抛出额外的异常。
回答by JSON C11
The caller of this method will need to either catch this exception or declare it to be rethrown in it's method signature.
此方法的调用者将需要捕获此异常或在其方法签名中声明将其重新抛出。
private void calculateArea() throws Exception {
// Do something
}
In the try-catch block example below. The caller of this method doesn't have to worry about handling the exception as it has already been taken care of.
在下面的 try-catch 块示例中。这个方法的调用者不必担心处理异常,因为它已经被处理了。
private void calculateArea() {
try {
// Do something
} catch (Exception e) {
showException(e);
}
}
回答by isaace
Many times you want the caller to handle the exception. Let's say you have the caller call a method which calls another method which calls another method, instead of having each method handle the exception, you can just handle it at the caller. Unless, you want to do something in one of the methods when that method fails.
很多时候你希望调用者处理异常。假设您让调用者调用一个调用另一个方法的方法,该方法调用另一个方法,而不是让每个方法处理异常,您可以在调用者处处理它。除非,当该方法失败时,您想在其中一种方法中执行某些操作。
回答by Sherif Eldeeb
If you threw an exception, the child method (which overrides this) should handle the exception
如果您抛出异常,则子方法(覆盖此)应处理异常
example:
例子:
class A{
public void myMethod() throws Exception{
//do something
}
}
A a=new A();
try{
a.myMethod();
}catch Exception(e){
//handle the exception
}
回答by Nitin Pawar
private void calculateArea() throws Exception {
....do something
}
This throws the exception,so the caller is responsible for handling that exception but if caller does not handle the exception then may be it will given to jvm which may result in abnormal termination of programe.
这会引发异常,因此调用者负责处理该异常,但如果调用者不处理异常,则可能会将其交给 jvm,这可能会导致程序异常终止。
Whereas in second case:
而在第二种情况下:
private void calculateArea() {
try {
....do something
} catch (Exception e) {
showException(e);
}
}
Here the exception is handled by the callee,so there is no chance of abnormal termination of the program.
这里的异常是由被调用者处理的,所以程序不会异常终止。
Try-catchis the recommended approach.
Try-catch是推荐的方法。
IMO,
海事组织,
Throws keyword mostly used with Checked exceptions to convince compiler but it does not guarantees normal termination of program.
Throws keyword delegate the responsibility of exception handling to
the caller(JVM or another method).Throws keyword is required for checked exceptions only ,for unchecked exceptions there is no use of throws keyword.
Throws 关键字主要与 Checked 异常一起使用以说服编译器,但它不保证程序的正常终止。
抛出关键字将异常处理的责任委托给
调用者(JVM 或其他方法)。只有检查异常才需要 Throws 关键字,对于未检查异常,不使用 throws 关键字。