在Java中处理RuntimeExceptions

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

它与处理常规exception没有区别:

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

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

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

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

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

不确定你是否在Java中直接引用RuntimeException ,所以我假设你在谈论运行时exception。

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

 try { // Do something here } 

然后,您处理exception。

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

如果无论是否引发exception,您都需要执行某些操作,请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 { }