Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Friday, 5 July 2013

Sun Tech Tip

CATCHING UNCAUGHT EXCEPTIONS



The March 16, 2004 Tech Tip Best Practices in Exception Handling described several best practices for handling exceptions. In this tip you'll learn about an additional way of handling exceptions, that is, through the UncaughtExceptionHandler, which was added in J2SE 5.0.

As its name implies, the UncaughtExceptionHandler handles uncaught exceptions. More specifically, it handles uncaught runtime exceptions. The java compiler requires all non-runtime exceptions to be handled, otherwise the program won't compile. Here "handled" means that exceptions are declared in the throws clause of the declaring method or caught in the catch clause of a try-catch block.

To demonstrate, lets look at two exceptions: FileNotFoundException and ArithmeticException. Calling the constructor for FileReader with either a String or File argument throws a FileNotFoundException if the provided location does not point to a valid regular file. The compiler requires that when you call either of these constructors, you handle the thrown exception:
   FileReader input;
String filename = ...;
try {
input = new FileReader(filename);
} catch (FileNotFoundException e) {
processMissingFile(filename, e);
}
By comparison, an ArithmeticException is a type of runtime exception. The Java programming language specification (and so too the compiler) doesn't require that runtime exceptions be handled. So the following loop, which divides by 100 the numbers from 10-to-0, throws an ArithmeticException on the final pass through the loop:
   for (int i=10; i >= 0; i--) {
int div = 100 / i;
}

Exception in thread "main" java.lang.ArithmeticException: /
by zero
at Test.main(Test.java:4)
Printing the stack trace is what the default uncaught exception handler does. Typically, this default behavior is sufficient, but sometimes it isn't. Imagine that you want to show the stack trace in a popup window, instead of dumping the trace to the system console. By installing your own default uncaught exception handler, you can get this behavior.

There are at least three ways to install an uncaught exception handler. First, you can call the setUncaughtExceptionHandler() method of Thread. This allows you to customize the behavior for a specific thread. Second, you can define your own ThreadGroup and change the behavior of any threads created in the group by overriding their uncaughtException() method. Third, you can set the default behavior for all threads by calling the static setDefaultUncaughtExceptionHandler() method of Thread.

Both the setUncaughtExceptionHandler() and setDefaultUncaughtExceptionHandler() methods of Thread accept an implementation of the UncaughtExceptionHandler interface an argument. The interface is an inner interface of the Thread class so its full name is Thread.UncaughtExceptionHandler. This interface has a single method:
   void uncaughtException(Thread t, Throwable e)
You can get the customized behavior by providing an implementation of the uncaughtException method, either as part of your custom implementation of the interface or as an overridden method of ThreadGroup. To demonstrate, here's an implementation of UncaughtExceptionHandler that shows a window with the stack trace appended to end of a text area whenever a runtime exception is encountered. You can close the window between exceptions. The window will reappear in front of other windows when the next exception happens.
   import java.awt.*;
import java.io.*;
import javax.swing.*;

public class StackWindow extends JFrame
implements Thread.UncaughtExceptionHandler {

private JTextArea textArea;

public StackWindow(
String title, final int width, final int height) {
super(title);
setSize(width, height);
textArea = new JTextArea();
JScrollPane pane = new JScrollPane(textArea);
textArea.setEditable(false);
getContentPane().add(pane);
}

public void uncaughtException(Thread t, Throwable e) {
addStackInfo(e);
}

public void addStackInfo(final Throwable t) {
EventQueue.invokeLater(new Runnable() {
public void run() {
// Bring window to foreground
setVisible(true);
toFront();
// Convert stack dump to string
StringWriter sw = new StringWriter();
PrintWriter out = new PrintWriter(sw);
t.printStackTrace(out);
// Add string to end of text area
textArea.append(sw.toString());
}
});
}
}
To test the handler, you need a program that installs the handler and then throws some runtime exceptions. The following program, DumpTest, does that. For simplicity, DumpTest only generates two exceptions. Feel free to add more troublesome code to the program, with more exceptions thrown. The program pauses between exceptions to show that you can close the exception dump stack window between exceptions.
   import java.io.*;

public class DumpTest {
public static void main(final String args[])
throws Exception {
Thread.UncaughtExceptionHandler handler =
new StackWindow("Show Exception Stack", 400, 200);
Thread.setDefaultUncaughtExceptionHandler(handler);
new Thread() {
public void run() {
System.out.println(1 / 0);
}
}.start();
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
System.out.print("Press Enter for next exception");
br.readLine();
new Thread() {
public void run() {
System.out.println(args[0]);
}
}.start();
System.out.print("Press Enter to end");
br.readLine();
System.exit(0);
}
}
Compile StackWindow and DumpTest. When you run DumpTest, you should see the follow in your console:
   > java DumpTest
Press Enter for next exception
You'll also see a window with the stack trace for an exception in the text area.

UncaughtExceptionWindow Window

Press Enter, and you should see the following in your console:
   Press Enter to end
You should also see another stack trace appended to the text area in the window.

UncaughtExceptionWindow Window

Although you might think that this is all there is to handling uncaught exceptions, there is more. Modal dialogs require their own event thread and because of that, their own uncaught handler. The system property sun.awt.exception.handler does cover all cases, but is not well documented. An RFE (request for enhancement) has been submitted to expand the property into a formal API.

In addition to the Best Practices tip on exception handling, the May 2002 tip on StackTraceElements is another useful point of reference. See also the lesson Handling Errors Using Exceptions in The Java Tutorial.

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...