When to catch java.lang.Error?

2018-12-31 20:17发布

In what situations should one catch java.lang.Error on an application?

16条回答
旧人旧事旧时光
2楼-- · 2018-12-31 20:49

If you are crazy enough to be creating a new unit test framework, your test runner will probably need to catch java.lang.AssertionError thrown by any test cases.

Otherwise, see other answers.

查看更多
深知你不懂我心
3楼-- · 2018-12-31 20:51

Generally, never. However, sometimes you need to catch specific Errors.

If you're writing framework-ish code (loading 3rd party classes), it might be wise to catch LinkageErrors (no class def found, unsatisfied link, incompatible class change). I've also seen some stupid 3rd-party code throwing sublcasses of Errors, so you'll have to handle these either.

By the way, I'm not sure it isn't possible to recover from OutOfMemory.

查看更多
零度萤火
4楼-- · 2018-12-31 20:51

Very, very rarely.

I did it only for one very very specific known cases. For example, java.lang.UnsatisfiedLinkError could be throw if two independence ClassLoader load same DLL. (I agree that I should move the JAR to a shared classloader)

But most common case is that you needed logging in order to know what happened when user come to complain. You want a message or a popup to user, rather then silently dead.

Even programmer in C/C++, they pop an error and tell something people don't understand before it exit (e.g. memory failure).

查看更多
听够珍惜
5楼-- · 2018-12-31 20:52

It might be appropriate to catch error within unit tests that check an assertion is made. If someone disables assertions or otherwise deletes the assertion you would want to know

查看更多
泪湿衣
6楼-- · 2018-12-31 20:56

it's quite handy to catch java.lang.AssertionError in a test environment...

查看更多
旧人旧事旧时光
7楼-- · 2018-12-31 20:57

In multithreaded environment, you most often want to catch it! When you catch it, log it, and terminate whole application! If you don't do that, some thread that might be doing some crucial part would be dead, and rest of the application will think that everything is normal. Out of that, many unwanted situations can happen. One smallest problem is that you wouldn't be able to easily find root of the problem, if other threads start throwing some exceptions because of one thread not working.

For example, usually loop should be:

try {
   while (shouldRun()) {
       doSomething();
   }
}
catch (Throwable t) {
   log(t);
   stop();
   System.exit(1);
}

Even in some cases, you would want to handle different Errors differently, for example, on OutOfMemoryError you would be able to close application regularly (even maybe free some memory, and continue), on some others, there is not much you can do.

查看更多
登录 后发表回答