Sunday, January 8, 2012

Handling Uncaught Exceptions in Threads

Normally a Java thread (represented by any class that extends java.lang.Thread) stops when its
run( ) method completes. In an abnormal case, such as when something goes wrong, the thread can
terminate by throwing an exception. This exception trickles up the thread's ThreadGroup hierarchy,
and if it gets to the root ThreadGroup, the default behavior is to print out the thread's name,
exception name, exception message, and exception stack trace.
To get around this behavior (at least in Java 1.4 and earlier), you've got to insert your own code into
the ThreadGroup hierarchy, handle the exception, and prevent delegation back to the root
ThreadGroup. While this is certainly possible, you'll have to define your own subclass of
ThreadGroup, make sure any Threads you create are assigned to that group, and generally do a lot
of coding that has very little to do with the task at hand—actually handling the uncaught exception.
Tiger simplifies all this dramatically, and lets you define uncaught exception handling on a per-Thread basis.

Example:



package com.oreilly.tiger.ch10;


public class BubbleSortThread extends Thread {


private int[] numbers;


public BubbleSortThread(int[] numbers) {

setName("Simple Thread");

setUncaughtExceptionHandler(

new SimpleThreadExceptionHandler( ));

this.numbers = numbers;

}


public void run( ) {

int index = numbers.length;

boolean finished = false;

while (!finished) {

index--;

finished = true;

for (int i=0; i<5; i++)="" {="" create="" error="" condition="" if="" (numbers[i+1]="" <="" 0)="" throw="" new="" illegalargumentexception(="" "cannot="" pass="" negative="" numbers="" into="" this="" thread!");="" }="" (numbers[i]=""> numbers[i+1]) {

// swap

int temp = numbers[i];

numbers[i] = numbers[i+1];

numbers[i+1] = temp;



finished = false;

}

}

}

}

}



class SimpleThreadExceptionHandler implements

Thread.UncaughtExceptionHandler {



public void uncaughtException(Thread t, Throwable e) {

System.err.printf("%s: %s at line %d of %s%n",

t.getName( ),

e.toString( ),

e.getStackTrace( )[0].getLineNumber( ),

e.getStackTrace( )[0].getFileName( ));

}

}

0 comments:

Post a Comment

Tu comentario será moderado la primera vez que lo hagas al igual que si incluyes enlaces. A partir de ahi no ser necesario si usas los mismos datos y mantienes la cordura. No se publicarán insultos, difamaciones o faltas de respeto hacia los lectores y comentaristas de este blog.