开发者

Where is this exception caught and handled?

In some code I've been reading, I've come across this :

    class Someclass
    {
      public static void main(String[] args) throws IOException
      {
        //all other code here......
      }
    }

If main() throws an exception, in this case its an IOException, where is it caught and handled?

EDIT: Is this considered bad practice? Or is开发者_如何学Python this really common in real world code?


The detailed flowchart of full uncaught exception handling is given here: How uncaught exceptions are handled in Java.

When an uncaught exception occurs, the JVM does the following:

  • it calls a special private method, dispatchUncaughtException(), on the Thread class in which the exception occurs;
    • [...which] calls the thread's getUncaughtExceptionHandler() method to find out the appropriate uncaught exception handler to use. Normally, this will actually be the thread's parent ThreadGroup, whose handleException() method by default will print the stack trace.
  • it then terminates the thread in which the exception occurred.

Therefore you can, if you wish to, create your own custom uncaught exception handler.

It should also be noted that while main is commonly used as a Java application entry point, the method is just like any other methods in that it can also be called from other contexts (e.g. other main methods, or even itself recursively!). In that case, the caller can catch exceptions thrown.

public class SelfCatch {
    public static void main(String args[]) throws Exception {
        if (args == null) throw new Exception("Hi there!");
        try {
            main(null);
        } catch (Exception e) {
            System.out.println("Caught: " + e);
        }
        System.out.println("Exiting...");
    }
}

Output:

Caught: java.lang.Exception: Hi there!
Exiting...


EDIT: Is this considered bad practice? Or is this really common in real world code?

It would be in production code, but when rapid prototyping or knocking up test code its often used as its quicker than typing the try {...} catch block. (unless you use a good IDE like Eclipse 3.5 which has an 'Auto wrap in try/catch' feature [auto-detecting any and all exceptions to!] ;-) )

Or your pretty sure it wont be thrown by methods invoked by main().

But even wrapping in a try/catch block will usually result in the same output as if you leave the Exception uncaught, if you simply use e.printStackTrace() ...


At the command line.

EDIT: The entry point is Main. Hence, there is no other method/caller to handle the exception.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜