开发者

Can an Error be handled?

public class StackTest {
    public static void main(Str开发者_开发知识库ing[] args) {
        show();
        System.out.print("welcome back to maain");
        display();
    }
    static void show(){
        try{
            show();    //recursion
        }catch(StackOverflowError e){
            System.out.print("error cought");
        }
    }
    static void display(){
        System.out.print("after stack overflow error");
    }
}

In this program an StackOverflowError occurs but gets handled and the program does not terminated abnormally. why? You can see this at http://ideone.com/vwSav


You can handle Errors because they are Throwable just like Exceptions.

Errors are designed to indicate problems outside your program's control, like OutOfMemoryError and StackOverflowError, but you can define your own errors, too.

Perhaps you are thinking that, or heard that, OutOFMemoryError can be caught but there's no guarantee you'll have enough space to execute the handler, so errors must in general not be something you can catch. In your case, though, you got away with it. No language rules were violated in the catching and handling of this error.

The real question is, should you catch them? Normally when an error, as opposed to an exception, is thrown, your application is very likely in an inconsistent state, making recovery a crapshoot at best. So be really, really careful. Better to forget it and let the app die though, since whatever is running after the handler is not guaranteed to be something you'd want to run.


Why would you expect it to terminate when you catch the exception (or rather the Error in this case)? What else would that catch block do?

You can catch and handle pretty much all error conditions, though usually you should only catch Exceptions.


You can catch any Throwable and it is up to the developer to handle it correctly. You can even handle ThreadDeath (triggered by a Thread.stop()) or another sub-class of Throwable (which is neither an Error or an Exception)

public class MyThrowable extends Throwable { } // checked "exception"

try {
   throw new MyThrowable();
} catch (Throwable t) {
   t.printStackTrace();
   Thread.currentThread().stop(t); // rethrow blindly.
}


It will only be terminated abnormally if your exception is propagated all the way up to your main method and you don't handle it there. Usually happens for unchecked run time exceptions. If you want to terminate your program and shut down the VM you can call System.exit(int errorCode) in the catch block, there will be programmers which always complain here if that's done but that's a way to do it.


usually you don't catch Error, except for LinkageErrors, no class def found errors, unsatisfied link errors, incompatible class change errors..

also an outofmemory error (sometimes the stackoverflow exception) doesnot give control the catch block as there is no memory.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜