在Java中处理RuntimeExceptions

时间:2010-01-08 15:50:21

标签: java exception-handling runtimeexception

任何人都可以解释如何处理Java中的运行时异常吗?

4 个答案:

答案 0 :(得分:36)

与处理常规例外没有区别:

try {
   someMethodThatThrowsRuntimeException();
} catch (RuntimeException ex) {
   // do something with the runtime exception
}

答案 1 :(得分:4)

如果您知道可能抛出的异常类型,则可以明确地捕获它。您也可以捕获Exception,但这通常被认为是非常糟糕的做法,因为您将以相同的方式处理所有类型的例外。

通常,RuntimeException的一个原因是您无法正常处理它,并且在程序的正常执行期间不会抛出它们。

答案 2 :(得分:2)

你就像其他任何例外一样抓住它们。

try {
   somethingThrowingARuntimeException()
}
catch (RuntimeException re) {
  // Do something with it. At least log it.
}

答案 3 :(得分:2)

不确定您是否在Java中直接引用RuntimeException,因此我假设您正在讨论运行时异常。

Java中异常处理的基本思想是封装您希望在特殊语句中引发异常的代码,如下所示。

try {
   // Do something here
}

然后,您处理异常。

catch (Exception e) {
   // Do something to gracefully fail
}

如果无论是否引发异常,您都需要执行某些操作,请添加finally

finally {
   // Clean up operation
}

所有这一切看起来都像这样。

try {
   // Do something here
}
catch (AnotherException ex) {
}
catch (Exception e) {  //Exception class should be at the end of catch hierarchy.
}
finally {
}