0

I came to know from question that when some Error like NoClassDefFoundError occurs in Java

This is a pretty critical error, as the program cannot be initiated by the JVM.

Then:

try {
    //statements
} catch (NoClassDefFoundError e) { // catching NoClassDefFoundError 
    e.printStackTrace();
    //do something when Error occurred
} catch(Error e){ // catching Error
    e.printStackTrace();
    //do something when Error occurred
}catch (Exception e) {
    e.printStackTrace();
    //do something when Exception occurred
}

Questions:

  • Does it have any significance by catching Error in try catch block as program will not be initiated by the JVM, will these block will ever execute?

  • If not then why catching mechanism for Error is allowed in Java. If yes then when and how?

Community
  • 1
  • 1
Vishrant
  • 10,695
  • 8
  • 48
  • 87
  • Do what when the error occurred? Whether it's an error or an exception, how would you expect to handle a problem like this? – Tony Hopkinson May 02 '14 at 11:59
  • possible duplicate of [When to catch java.lang.Error?](http://stackoverflow.com/questions/352780/when-to-catch-java-lang-error) – Raedwald May 02 '14 at 12:13

3 Answers3

1

You can catch errors. However, usually you should not do it, as you can't do anything about it in most cases. If an error occurs it is almost always to late to do anything about it. In some rare cases in might be useful to catch errors though: When to catch java.lang.Error?

Community
  • 1
  • 1
nils
  • 1,212
  • 1
  • 8
  • 15
1

Exception handling in java is meant to process the risky behaviour in your program but Errors stand for serious matters and should not be catched.

Generally speaking, it is non advised to catch Errors but only Exceptions (checked or unchecked). Here is lines from the JAVA API for Error:

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. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.

A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur. That is, Error and its subclasses are regarded as unchecked exceptions for the purposes of compile-time checking of exceptions.

Community
  • 1
  • 1
tmarwen
  • 11,491
  • 4
  • 35
  • 54
0

In cases where you are using custom classloaders to load classes, there could be scenarios, where the plugin jars (say, the custom classloaders are meant for loading the classes from these jars and these jars are created by users) could behave erratically during class loading. At these points of time, it is good to catch these kind of errors and log them.

As others pointed out, there is nothing much you can do about it.

Parasu
  • 182
  • 2
  • 12