捕捉Java错误 [英] Catching Java errors

查看:222
本文介绍了捕捉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.

让我们开始澄清什么是错误类。

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 class:异常错误。他们的文档中解释了这两者之间的区别:

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


一个错误 Throwable的子类 表示严重的
问题,合理的应用程序不应该试图抓住。大多数
这样的错误是异常情况。
[...]


异常及其子类是 Throwable
的一种形式,表示合理应用程序可能要
来捕获。

如上所述,由于不同的起源,错误和异常被分离。 错误通常表示一个问题,应用程序无法从恢复。因此,它们不应被捕获。

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 也是如此,但它用于指示高级层的问题(例如方法)。而错误表示低级问题(例如运行时)。

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.

我覆盖了上述(更详细和示例)和一些扩展信息,在我的博客上的文章

I covered the above (in more detail and with examples) and some extended information in an article on my Blog.

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

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