Centralized way of catching unexpected Exceptions in Java?
Hi Guys,
Is there a centralized way to catch unexpected Exceptions in Java?
Here's an example:
publicstaticvoid main(String[] args)
{
try
{
new Thread()
{
publicvoid run()
{
String s =null;
//NullPointerException is thrown here
s.indexOf(12);
}
}.start();
}
catch (Exception ex)
{
System.err.println("This is not called");
ex.printStackTrace();
}
}
Think about a program error, that the program is not prepared for, i.e. NullPointerException or an ArrayIndexOutOfBounds exception.
What I'm after is not like "put critical block in try-catch", but something like registering a global ExceptionListener in java.lang.Runtime, a monitoring MBean or something that I could use in my program to do a simple exception logging.
Any idea, help would be greatly appreciated!
peter
[1560 byte] By [
kp_a] at [2007-10-3 10:19:44]

NullPointerException , IOException ....all are subclasses of the base class Exception, so catch(Exception) will catch any exception in the current thread. So modify ur code a bit
...
public static void main(String[] args)
{
new Thread()
{
public void run()
{
try{
String s = null;
//NullPointerException is thrown here
s.indexOf(12);
}
catch (Exception ex)
{
System.err.println("This is not called");
ex.printStackTrace();
}
}
}.start();
}
.....
Hi AmitavaDey,
Thanks for the reply, but it's not exactly what I'm after.
What I'd like to achieve is to either catch or at least somehow be notified about the Exception in run() without putting try-catch in run().
Imagine that you have a number of Threads from various sources running inside your application. You don't have access to modify all source code, but still need to know about unexpected Exceptions at least for the purpose of logging them in the running program's logfile.
Peter
kp_a at 2007-7-15 5:40:59 >

Hi Guys, I've got one solution. After adding this to main(), I could catch all Exceptions I was after.
public static void main(String[] args) throws FileNotFoundException
{
Thread.currentThread().setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler()
{
public void uncaughtException(Thread t, Throwable e)
{
System.err.println(">>>>>>> " + t + " " + e);
e.printStackTrace();
}
});
...
}
Peter
kp_a at 2007-7-15 5:40:59 >
