处理 Java 中的运行时异常

发布于 2024-08-16 21:53:55 字数 1436 浏览 6 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

无名指的心愿 2024-08-23 21:53:55

它与处理常规异常没有什么不同:

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

It doesn't differ from handling a regular exception:

try {
   someMethodThatThrowsRuntimeException();
} catch (RuntimeException ex) {
   // do something with the runtime exception
}
枯寂 2024-08-23 21:53:55

如果您知道可能抛出的异常类型,则可以显式捕获它。您还可以捕获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.

怀念你的温柔 2024-08-23 21:53:55

你只需捕获它们,就像任何其他异常一样。

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

You just catch them, like any other exception.

try {
   somethingThrowingARuntimeException()
}
catch (RuntimeException re) {
  // Do something with it. At least log it.
}
并安 2024-08-23 21:53:55

不确定您是否直接引用 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 {
}

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 {
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文