Exception Catcher : Exceptions « Language Basics « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Collections Data Structure
8. Database SQL JDBC
9. Design Pattern
10. Development Class
11. Email
12. Event
13. File Input Output
14. Game
15. Hibernate
16. J2EE
17. J2ME
18. JDK 6
19. JSP
20. JSTL
21. Language Basics
22. Network Protocol
23. PDF RTF
24. Regular Expressions
25. Security
26. Servlets
27. Spring
28. Swing Components
29. Swing JFC
30. SWT JFace Eclipse
31. Threads
32. Tiny Application
33. Velocity
34. Web Services SOA
35. XML
Microsoft Office Word 2007 Tutorial
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
C# / C Sharp
C# / CSharp Tutorial
ASP.Net
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
PHP
Python
SQL Server / T-SQL
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Java » Language Basics » ExceptionsScreenshots 
Exception Catcher
Exception Catcher

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.URL;
import java.util.EventListener;
import java.util.EventObject;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class ExceptionCatcherTester {
  public ExceptionCatcherTester() {
    JFrame f = new JFrame("Exception Catcher Tester");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    final JTextArea textArea = new JTextArea();
    textArea.setEditable(false);

    JButton button = new JButton("Alive");
    ActionListener buttonListener = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("I'm Alive");
      }
    };
    button.addActionListener(buttonListener);

    final JTextField textField = new JTextField();
    ActionListener textFieldListener = new ActionListener() {
      public void actionPerformed(final ActionEvent e) {
        // Code to load URL contents in separate thread
        Runnable r = new Runnable() {
          public void run() {
            textField.setEditable(false);
            String urlString = e.getActionCommand();
            try {
              System.out.println("Loading " + urlString);
              textArea.setText("");
              URL url = new URL(urlString);
              InputStream is = url.openStream();
              InputStreamReader isr = new InputStreamReader(is);
              BufferedReader br = new BufferedReader(isr);
              StringWriter sw = new StringWriter();
              char buf[] new char[1024];
              int count;
              while ((count = br.read(buf, 01024)) != -1) {
                sw.write(buf, 0, count);
              }
              System.out.println("Done Loading");
              updateTextArea(textArea, sw.toString());
            catch (IOException e) {
              throw new ThreadException(this, e);
            finally {
              textField.setEditable(true);
            }
          }
        };
        ExceptionCatcherThread runner = new ExceptionCatcherThread(r);

        // Listener in case of exception
        ThreadListener threadListener = new ThreadListener() {
          public void exceptionHappened(ThreadException e) {
            Throwable t = e.getSourceException();
            final String message = t.getClass().getName() ": "
                + t.getMessage();
            Runnable r = new Runnable() {
              public void run() {
                JOptionPane.showMessageDialog(null, message);
              }
            };
            SwingUtilities.invokeLater(r);
          }
        };
        runner.addThreadExceptionListener(threadListener);

        runner.start();
      }
    };
    textField.addActionListener(textFieldListener);
    Container c = f.getContentPane();
    c.add(textField, BorderLayout.NORTH);
    JScrollPane pane = new JScrollPane(textArea);
    c.add(pane, BorderLayout.CENTER);
    c.add(button, BorderLayout.SOUTH);
    f.setSize(300300);
    f.show();
  }

  public void updateTextArea(final JTextArea ta, final String text) {
    // Because file loading happening not blocking event thread
    // We have to set text area in event thread
    Runnable r = new Runnable() {
      public void run() {
        ta.setText(text);
        ta.setCaretPosition(0);
      }
    };
    SwingUtilities.invokeLater(r);
  }

  public static void main(String args[]) {
    new ExceptionCatcherTester();
  }
}

class ExceptionCatcherThread extends ThreadGroup {

  private Runnable runnable;

  private Thread runner;

  private Vector listenerList = new Vector(3);

  /* For autonumbering our group. */
  private static int threadInitNumber;

  private static synchronized int nextThreadNum() {
    return threadInitNumber++;
  }

  public ExceptionCatcherThread(Runnable r) {
    super("ExceptionCatcherThread-" + nextThreadNum());
    runnable = r;
    // Create thread in this group
    runner = new Thread(this, runnable);
  }

  public void start() {
    runner.start();
  }

  /* Listener registration methods */

  public synchronized void addThreadExceptionListener(ThreadListener t) {
    listenerList.add(t);
  }

  public synchronized void removeThreadExceptionListener(ThreadListener t) {
    listenerList.remove(t);
  }

  public void uncaughtException(Thread source, Throwable t) {
    fireExceptionHappened(t);
    super.uncaughtException(source, t);
  }

  protected void fireExceptionHappened(Throwable t) {
    ThreadException e = (instanceof ThreadException(ThreadExceptiont
        new ThreadException(runnable, t);
    Vector l;
    synchronized (this) {
      l = (VectorlistenerList.clone();
    }
    for (int i = 0, n = listenerList.size(); i < n; i++) {
      ThreadListener tl = (ThreadListenerl.get(i);
      tl.exceptionHappened(e);
    }
  }
}

class ThreadException extends RuntimeException {
  Runnable runnable;

  Throwable exception;

  public ThreadException(Runnable r, Throwable t) {
    runnable = r;
    exception = t;
  }

  public ThreadException(Runnable r, Throwable t, String message) {
    super(message);
    runnable = r;
    exception = t;
  }

  public Runnable getRunnable() {
    return runnable;
  }

  public Throwable getSourceException() {
    return exception;
  }
}

class ThreadExceptionEvent extends EventObject {
  public ThreadExceptionEvent(ThreadException source) {
    super(source);
  }

  public Runnable getRunnable() {
    ThreadException source = (ThreadExceptiongetSource();
    return (Runnablesource.getRunnable();
  }
}

interface ThreadListener extends EventListener {
  public void exceptionHappened(ThreadException e);
}

           
       
Related examples in the same category
1. Illustrate various Exceptions Illustrate various Exceptions
2. Experience exceptionsExperience exceptions
3. StackTrace
4. What happens if a method declares an unchecked exception?
5. Simple demo of exceptionsSimple demo of exceptions
6. Simple demo of exceptions, with finally clauseSimple demo of exceptions, with finally clause
7. ThreadBasedCatcher - Demonstrate catching uncaught exceptions
8. Turning off Checked exceptions
9. Demonstrates exception chainingDemonstrates exception chaining
10. Finally is always executedFinally is always executed
11. Demonstrating the Exception MethodsDemonstrating the Exception Methods
12. Further embellishment of exception classesFurther embellishment of exception classes
13. The finally clause is always executedThe finally clause is always executed
14. Your own Exception classYour own Exception class
15. Catching exception hierarchiesCatching exception hierarchies
16. How an exception can be lost
17. Exception in main method
18. Ignoring RuntimeExceptionsIgnoring RuntimeExceptions
19. Demonstrating fillInStackTrace()Demonstrating fillInStackTrace()
20. Rethrow a different object from the one that was caughtRethrow a different object from the one that was caught
21. Inheriting your own exceptionsInheriting your own exceptions
22. Overridden methods may throw only the exceptions
23. Throw Exception OutThrow Exception Out
w___w__w___.___ja_va_2__s.___co_m_ | Contact Us
Copyright 2003 - 08 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.