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.
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.
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 {
}
Not sure if you're referring directly to RuntimeException in Java, so I'll assume you're talking about run-time exceptions.
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.
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 {
// 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 {
}
发布评论
评论(4)
它与处理常规异常没有什么不同:
It doesn't differ from handling a regular exception:
如果您知道可能抛出的异常类型,则可以显式捕获它。您还可以捕获
Exception
,但这通常被认为是非常糟糕的做法,因为您将以相同的方式处理所有类型的异常。一般来说,RuntimeException 的要点是您无法优雅地处理它,并且在程序的正常执行期间不会抛出它们。
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.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.
你只需捕获它们,就像任何其他异常一样。
You just catch them, like any other exception.
不确定您是否直接引用 Java 中的 RuntimeException,因此我假设您正在谈论运行时异常。
Java 中异常处理的基本思想是,将预期可能引发异常的代码封装在特殊语句中,如下所示。
然后,您处理异常。
如果无论是否引发异常都需要执行某些操作,请添加
finally
。总的来说,它看起来像这样。
Not sure if you're referring directly to
RuntimeException
in Java, so I'll assume you're talking about run-time exceptions.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.
Then, you handle the exception.
If you need certain things to execute regardless of whether an exception is raised, add
finally
.All together it looks like this.