在 Java 中处理运行时异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2028719/
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
Handling RuntimeExceptions in Java
提问by RKCY
Can anyone explain how to handle the Runtime Exceptions in Java?
谁能解释一下如何在 Java 中处理运行时异常?
采纳答案by Bozho
It doesn't differ from handling a regular exception:
它与处理常规异常没有区别:
try {
someMethodThatThrowsRuntimeException();
} catch (RuntimeException ex) {
// do something with the runtime exception
}
回答by danben
If you know the type of Exception that might be thrown, you could catch it explicitly. You could also catch Exception
, but this is generally considered to be very bad practice because you would then be treating Exceptions of all types the same way.
如果您知道可能抛出的 Exception 类型,则可以明确地捕获它。您也可以 catch Exception
,但这通常被认为是非常糟糕的做法,因为您会以相同的方式处理所有类型的异常。
Generally the point of a RuntimeException is that you can't handle it gracefully, and they are not expected to be thrown during normal execution of your program.
通常 RuntimeException 的重点是你不能优雅地处理它,并且在你的程序正常执行期间它们不会被抛出。
回答by Confusion
You just catch them, like any other exception.
你只需抓住它们,就像任何其他例外一样。
try {
somethingThrowingARuntimeException()
}
catch (RuntimeException re) {
// Do something with it. At least log it.
}
回答by Ed Altorfer
Not sure if you're referring directly to RuntimeException
in Java, so I'll assume you're talking about run-time exceptions.
不确定您是否RuntimeException
在 Java 中直接引用,所以我假设您在谈论运行时异常。
The basic idea of exception handling in Java is that you encapsulate the code you expect might raise an exception in a special statement, like below.
Java 中异常处理的基本思想是将预期可能引发异常的代码封装在特殊语句中,如下所示。
try {
// Do something here
}
Then, you handle the exception.
然后,您处理异常。
catch (Exception e) {
// Do something to gracefully fail
}
If you need certain things to execute regardless of whether an exception is raised, add finally
.
如果无论是否引发异常都需要执行某些事情,请添加finally
.
finally {
// Clean up operation
}
All together it looks like this.
放在一起看起来像这样。
try {
// Do something here
}
catch (AnotherException ex) {
}
catch (Exception e) { //Exception class should be at the end of catch hierarchy.
}
finally {
}