捕获 Java 错误 [英] Catching Java errors

查看:17
本文介绍了捕获 Java 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说捕捉 java.lang.Error 被认为是不好的做法.我目前正在加载一个不能保证在 PATH 上的 .dll,如果不是,我想切换到用户配置的位置.

I've heard that catching java.lang.Error is considered bad practice. I'm currently loading a .dll that is not guaranteed to be on the PATH, and would like to switch to a user-configured location in the case that it isn't.

try {
    System.loadLibrary("HelloWorld");
} catch(UnsatisfiedLinkError ule){
    System.load("C:/libraries/HelloWorld.dll");
}

有没有更好的方法来做到这一点?或者在此处捕获 UnsatisfiedLinkError 是否可以接受?

Is there a better way of doing this? Or is catching the UnsatisfiedLinkError here acceptable?

推荐答案

除了就如何从技术上解决问题给出建议之外,我想先花点时间解释一下为什么它首先被认为是不好的做法".

Other than giving advice on how to technically overcome the problem, I'd like to take a moment and explain why it's considered "bad practice" in the first place.

让我们首先阐明 Error 类是什么.

Let's start off by clarifying what the Error class is.

在java中,会抛出错误和异常(这是主要的类型).使用 throw 关键字可以抛出上述之一.扩展基本 java.lang.Throwable 的每个类都可以抛出.

In java, errors and exceptions (which are the main types) are thrown. Throwing one of the above is done by using the throw keyword. Every class which extends the basic java.lang.Throwable can be thrown.

有两个类继承自基本的Throwable 类:ExceptionError.他们的文档中解释了这两者之间的区别:

There are two classes which inherit from the basic Throwable class: Exception and Error. The difference between those two is explained in their documentations:

ErrorThrowable 的子类,表示严重合理的应用程序不应试图捕捉的问题.最多此类错误属于异常情况. [...]

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. [...]

来源

Exception 类及其子类是 Throwable 的一种形式表示合理的应用程序可能需要的条件捕捉.

The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.

来源

如上所述,错误和异常是分开的,因为它们的来源不同.Error 通常表示存在问题,应用程序无法从中恢复.因此,他们不应该被抓住.

As explained above, errors and exceptions are separated because of their different origins. An Error normally indicates a problem, which the application can not recover from. Therefore, they should not be caught.

对于 RuntimeException 也是如此,但它用于指示高级层(例如方法)的问题.而 Error 表示低级问题(例如运行时).

The same is true for a RuntimeException, but it is used to indicate a problem with a high-level layer (e.g. methods). Whereas the Error indicates a low-level problem (e.g. the runtime).

因此,既然您了解了您应该只捕获可以从中恢复的异常和错误,那么您的问题的答案应该很清楚了.

So, now that you understood that you shall only catch exceptions and errors which you are able to recover from, the answer to your question should be clear.

是的,捕获 UnsatisfiedLinkError 是完全合理的,因为您的应用程序可以从中恢复.

Yes, it's perfectly reasonable to catch the UnsatisfiedLinkError, because your application can recover from it.

我在关于我的文章中介绍了上述内容(更详细并附有示例)和一些扩展信息博客.

这篇关于捕获 Java 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆