有人能解释一下如何在Java中处理运行时异常吗?
有人能解释一下如何在Java中处理运行时异常吗?
处理它与处理常规异常没有区别:
try {
someMethodThatThrowsRuntimeException();
} catch (RuntimeException ex) {
// do something with the runtime exception
}
Throwable
的所有子类都可以被捕获。 - Carl Smotricztry {
somethingThrowingARuntimeException()
}
catch (RuntimeException re) {
// Do something with it. At least log it.
}
我不确定你是否直接指的是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 {
}
catch (ExceptionType name) {}
来捕获任何类型的异常。否则,你可以使用catch {}
来捕获所有异常,或者使用catch (Exception name) {}
来捕获所有异常(并且可以访问有关它们的信息)。 - Ed Altorfer