Java/Language Basics/Exceptions

Материал из Java эксперт
Версия от 18:01, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Содержание

A collection of utility methods for manipulating exceptions

 
/*
 * Copyright (c) 2003-2006, Simon Brown
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in
 *     the documentation and/or other materials provided with the
 *     distribution.
 *
 *   - Neither the name of Pebble nor the names of its contributors may
 *     be used to endorse or promote products derived from this software
 *     without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
import java.io.PrintWriter;
import java.io.StringWriter;
/**
 * A collection of utility methods for manipulating exceptions.
 *
 * @author    Simon Brown
 */
public final class ExceptionUtils {
  /**
   * Given a Throwable, this method returns a String representation of the
   * complete stack trace.
   *
   * @param t   the Throwable from which to extract the stack trace
   * @return  a String representation of the stack trace
   */
  public static String getStackTraceAsString(Throwable t) {
    if (t != null) {
      StringWriter sw = new StringWriter();
      PrintWriter writer = new PrintWriter(sw);
      t.printStackTrace(writer);
      return sw.getBuffer().toString();
    } else {
      return "";
    }
  }
}





Catching exception hierarchies

        
// : c09:Human.java
// Catching exception hierarchies.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
class Annoyance extends Exception {
}
class Sneeze extends Annoyance {
}
public class Human {
  public static void main(String[] args) {
    try {
      throw new Sneeze();
    } catch (Sneeze s) {
      System.err.println("Caught Sneeze");
    } catch (Annoyance a) {
      System.err.println("Caught Annoyance");
    }
  }
} ///:~





Convert an exception to a String with full stack trace

     
/**********************************************************************
Copyright (c) 2003 Andy Jefferson and others. All rights reserved. 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 
Contributors:
2003 Erik Bengtson - moved replaceAll from Column class to here
2004 Andy Jefferson - moved intArrayToString, booleanArrayToString from SM
2007 Xuan Baldauf - toJVMIDString hex fix
    ...
**********************************************************************/

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URLDecoder;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.jar.JarFile;
/**
 * Utilities for String manipulation.
 *
 * @version $Revision: 1.23 $   
 **/
public class StringUtils
{
  /**
   * Convert an exception to a String with full stack trace
   * @param ex the exception
   * @return a String with the full stacktrace error text
   */
  public static String getStringFromStackTrace(Throwable ex)
  {
      if (ex==null)
      {
          return "";
      }
      StringWriter str = new StringWriter();
      PrintWriter writer = new PrintWriter(str);
      try
      {
          ex.printStackTrace(writer);
          return str.getBuffer().toString();
      }
      finally
      {
          try
          {
              str.close();
              writer.close();
          }
          catch (IOException e)
          {
              //ignore
          }
      }
  }
}





Create a new Exception, setting the cause if possible.

    
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.    
 */
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
/**
 * Use this to create a new Exception.  This will run under JDK 1.3 or greater.
 * However, it running under JDK 1.4 it will set the cause.
 *
 * @author 
 * @since 1.5
 */
public class ExceptionUtils
{
    private static boolean causesAllowed = true;
    /**
     * Create a new RuntimeException, setting the cause if possible.
     * @param message
     * @param cause
     * @return A runtime exception object.
     */
    public static RuntimeException createRuntimeException(
            String message, Throwable cause)
    {
        return (RuntimeException) createWithCause(
                RuntimeException.class, message, cause);
    }
    /**
     * Create a new Exception, setting the cause if possible.
     * @param clazz
     * @param message
     * @param cause
     * @return A Throwable.
     */
    public static Throwable createWithCause(Class clazz,
            String message, Throwable cause)
    {
        Throwable re = null;
        if (causesAllowed)
        {
            try
            {
                Constructor constructor = clazz
                        .getConstructor(new Class[]{String.class,
                                Throwable.class});
                re = (Throwable) constructor
                        .newInstance(new Object[]{message, cause});
            }
            catch (RuntimeException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                causesAllowed = false;
            }
        }
        if (re == null)
        {
            try
            {
                Constructor constructor = clazz
                        .getConstructor(new Class[]{String.class});
                re = (Throwable) constructor
                        .newInstance(new Object[]{message
                                + " caused by " + cause});
            }
            catch (RuntimeException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw new RuntimeException("Error caused " + e); // should be impossible
            }
        }
        return re;
    }
    /**
     * Set the cause of the Exception.  Will detect if this is not allowed.
     * @param onObject
     * @param cause
     */
    public static void setCause(Throwable onObject, Throwable cause)
    {
        if (causesAllowed)
        {
            try
            {
                Method method = onObject.getClass().getMethod("initCause", new Class[]{Throwable.class});
                method.invoke(onObject, new Object[]{cause});
            }
            catch (RuntimeException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                causesAllowed = false;
            }
        }
    }
}





Create a new RuntimeException, setting the cause if possible.

    
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.    
 */
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
/**
 * Use this to create a new Exception.  This will run under JDK 1.3 or greater.
 * However, it running under JDK 1.4 it will set the cause.
 *
 * @author 
 * @since 1.5
 */
public class ExceptionUtils
{
    private static boolean causesAllowed = true;
    /**
     * Create a new RuntimeException, setting the cause if possible.
     * @param message
     * @param cause
     * @return A runtime exception object.
     */
    public static RuntimeException createRuntimeException(
            String message, Throwable cause)
    {
        return (RuntimeException) createWithCause(
                RuntimeException.class, message, cause);
    }
    /**
     * Create a new Exception, setting the cause if possible.
     * @param clazz
     * @param message
     * @param cause
     * @return A Throwable.
     */
    public static Throwable createWithCause(Class clazz,
            String message, Throwable cause)
    {
        Throwable re = null;
        if (causesAllowed)
        {
            try
            {
                Constructor constructor = clazz
                        .getConstructor(new Class[]{String.class,
                                Throwable.class});
                re = (Throwable) constructor
                        .newInstance(new Object[]{message, cause});
            }
            catch (RuntimeException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                causesAllowed = false;
            }
        }
        if (re == null)
        {
            try
            {
                Constructor constructor = clazz
                        .getConstructor(new Class[]{String.class});
                re = (Throwable) constructor
                        .newInstance(new Object[]{message
                                + " caused by " + cause});
            }
            catch (RuntimeException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw new RuntimeException("Error caused " + e); // should be impossible
            }
        }
        return re;
    }
    /**
     * Set the cause of the Exception.  Will detect if this is not allowed.
     * @param onObject
     * @param cause
     */
    public static void setCause(Throwable onObject, Throwable cause)
    {
        if (causesAllowed)
        {
            try
            {
                Method method = onObject.getClass().getMethod("initCause", new Class[]{Throwable.class});
                method.invoke(onObject, new Object[]{cause});
            }
            catch (RuntimeException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                causesAllowed = false;
            }
        }
    }
}





Demonstrates exception chaining

        
// : c09:DynamicFields.java
// A Class that dynamically adds fields to itself.
// Demonstrates exception chaining.
// {ThrowsException}
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
class DynamicFieldsException extends Exception {
}
public class DynamicFields {
  private Object[][] fields;
  public DynamicFields(int initialSize) {
    fields = new Object[initialSize][2];
    for (int i = 0; i < initialSize; i++)
      fields[i] = new Object[] { null, null };
  }
  public String toString() {
    StringBuffer result = new StringBuffer();
    for (int i = 0; i < fields.length; i++) {
      result.append(fields[i][0]);
      result.append(": ");
      result.append(fields[i][1]);
      result.append("\n");
    }
    return result.toString();
  }
  private int hasField(String id) {
    for (int i = 0; i < fields.length; i++)
      if (id.equals(fields[i][0]))
        return i;
    return -1;
  }
  private int getFieldNumber(String id) throws NoSuchFieldException {
    int fieldNum = hasField(id);
    if (fieldNum == -1)
      throw new NoSuchFieldException();
    return fieldNum;
  }
  private int makeField(String id) {
    for (int i = 0; i < fields.length; i++)
      if (fields[i][0] == null) {
        fields[i][0] = id;
        return i;
      }
    // No empty fields. Add one:
    Object[][] tmp = new Object[fields.length + 1][2];
    for (int i = 0; i < fields.length; i++)
      tmp[i] = fields[i];
    for (int i = fields.length; i < tmp.length; i++)
      tmp[i] = new Object[] { null, null };
    fields = tmp;
    // Reursive call with expanded fields:
    return makeField(id);
  }
  public Object getField(String id) throws NoSuchFieldException {
    return fields[getFieldNumber(id)][1];
  }
  public Object setField(String id, Object value)
      throws DynamicFieldsException {
    if (value == null) {
      // Most exceptions don"t have a "cause" constructor.
      // In these cases you must use initCause(),
      // available in all Throwable subclasses.
      DynamicFieldsException dfe = new DynamicFieldsException();
      dfe.initCause(new NullPointerException());
      throw dfe;
    }
    int fieldNumber = hasField(id);
    if (fieldNumber == -1)
      fieldNumber = makeField(id);
    Object result = null;
    try {
      result = getField(id); // Get old value
    } catch (NoSuchFieldException e) {
      // Use constructor that takes "cause":
      throw new RuntimeException(e);
    }
    fields[fieldNumber][1] = value;
    return result;
  }
  public static void main(String[] args) {
    DynamicFields df = new DynamicFields(3);
    System.out.println(df);
    try {
      df.setField("d", "A value for d");
      df.setField("number", new Integer(47));
      df.setField("number2", new Integer(48));
      System.out.println(df);
      df.setField("d", "A new value for d");
      df.setField("number3", new Integer(11));
      System.out.println(df);
      System.out.println(df.getField("d"));
      Object field = df.getField("a3"); // Exception
    } catch (NoSuchFieldException e) {
      throw new RuntimeException(e);
    } catch (DynamicFieldsException e) {
      throw new RuntimeException(e);
    }
  }
} ///:~





Demonstrating fillInStackTrace()

        
// : c09:Rethrowing.java
// Demonstrating fillInStackTrace()
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
public class Rethrowing {
  public static void f() throws Exception {
    System.out.println("originating the exception in f()");
    throw new Exception("thrown from f()");
  }
  public static void g() throws Throwable {
    try {
      f();
    } catch (Exception e) {
      System.err.println("Inside g(),e.printStackTrace()");
      e.printStackTrace();
      throw e; // 17
      // throw e.fillInStackTrace(); // 18
    }
  }
  public static void main(String[] args) throws Throwable {
    try {
      g();
    } catch (Exception e) {
      System.err.println("Caught in main, e.printStackTrace()");
      e.printStackTrace();
    }
  }
} ///:~





Demonstrating the Exception Methods

        
// : c09:ExceptionMethods.java
// Demonstrating the Exception Methods.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
public class ExceptionMethods {
  public static void main(String[] args) {
    try {
      throw new Exception("My Exception");
    } catch (Exception e) {
      System.err.println("Caught Exception");
      System.err.println("getMessage():" + e.getMessage());
      System.err.println("getLocalizedMessage():"
          + e.getLocalizedMessage());
      System.err.println("toString():" + e);
      System.err.println("printStackTrace():");
      e.printStackTrace();
    }
  }
} ///:~





Display Stack Trace Information with StackTraceElement

    
public class StackTrace {
  public static boolean displayStackTraceInformation(Throwable ex) {
    ex.printStackTrace();
    StackTraceElement[] stackElements = ex.getStackTrace();
    System.out.println("The " + stackElements.length + " element"
          + ((stackElements.length == 1) ? "" : "s") + " of the stack trace:\n");
    
    for (int lcv = 0; lcv < stackElements.length; lcv++) {
      System.out.println("File name: " + stackElements[lcv].getFileName());
      System.out.println("Line number: " + stackElements[lcv].getLineNumber());
      String className = stackElements[lcv].getClassName();
      String packageName = extractPackageName(className);
      String simpleClassName = extractSimpleClassName(className);
      System.out.println("Package name: " + ("".equals(packageName) ? "[default package]" : packageName));
      System.out.println("Full class name: " + className);
      System.out.println("Simple class name: " + simpleClassName);
      System.out.println("Unmunged class name: " + unmungeSimpleClassName(simpleClassName));
      System.out.println("Direct class name: " + extractDirectClassName(simpleClassName));
      System.out.println("Method name: " + stackElements[lcv].getMethodName());
      System.out.println("Native method?: " + stackElements[lcv].isNativeMethod());
      System.out.println("toString(): " + stackElements[lcv].toString());
      System.out.println("");
    }
    return true;
  }
  public static String extractPackageName(String fullClassName) {
    if ((null == fullClassName) || ("".equals(fullClassName)))
      return "";
    int lastDot = fullClassName.lastIndexOf(".");
    if (0 >= lastDot)
      return "";
    return fullClassName.substring(0, lastDot);
  }
  public static String extractSimpleClassName(String fullClassName) {
    if ((null == fullClassName) || ("".equals(fullClassName)))
      return "";
    int lastDot = fullClassName.lastIndexOf(".");
    if (0 > lastDot)
      return fullClassName;
    return fullClassName.substring(++lastDot);
  }
  public static String extractDirectClassName(String simpleClassName) {
    if ((null == simpleClassName) || ("".equals(simpleClassName)))
      return "";
    int lastSign = simpleClassName.lastIndexOf("$");
    if (0 > lastSign)
      return simpleClassName;
    return simpleClassName.substring(++lastSign);
  }
  public static String unmungeSimpleClassName(String simpleClassName) {
    if ((null == simpleClassName) || ("".equals(simpleClassName)))
      return "";
    return simpleClassName.replace("$", ".");
  }
}





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, 0, 1024)) != -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(300, 300);
    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 = (t instanceof ThreadException) ? (ThreadException) t
        : new ThreadException(runnable, t);
    Vector l;
    synchronized (this) {
      l = (Vector) listenerList.clone();
    }
    for (int i = 0, n = listenerList.size(); i < n; i++) {
      ThreadListener tl = (ThreadListener) l.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 = (ThreadException) getSource();
    return (Runnable) source.getRunnable();
  }
}
interface ThreadListener extends EventListener {
  public void exceptionHappened(ThreadException e);
}





Exception in main method

        
// : c09:MainException.java
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.io.FileInputStream;
public class MainException {
  // Pass all exceptions to the console:
  public static void main(String[] args) throws Exception {
    // Open the file:
    FileInputStream file = new FileInputStream("MainException.java");
    // Use the file ...
    // Close the file:
    file.close();
  }
} ///:~





Experience exceptions

        
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileInputStream;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class ExceptTest extends JFrame implements ActionListener {
    private double[] a;
  private JRadioButton divideByZeroButton;
  private JRadioButton badCastButton;
  private JRadioButton arrayBoundsButton;
  private JRadioButton nullPointerButton;
  private JRadioButton negSqrtButton;
  private JRadioButton overflowButton;
  private JRadioButton noSuchFileButton;
  private JRadioButton throwUnknownButton;
  public ExceptTest() {
    JPanel p = new JPanel();
    ButtonGroup g = new ButtonGroup();
    p.setLayout(new GridLayout(8, 1));
    divideByZeroButton = addRadioButton("Divide by zero", g, p);
    badCastButton = addRadioButton("Bad cast", g, p);
    arrayBoundsButton = addRadioButton("Array bounds", g, p);
    nullPointerButton = addRadioButton("Null pointer", g, p);
    negSqrtButton = addRadioButton("sqrt(-1)", g, p);
    overflowButton = addRadioButton("Overflow", g, p);
    noSuchFileButton = addRadioButton("No such file", g, p);
    throwUnknownButton = addRadioButton("Throw unknown", g, p);
    getContentPane().add(p);
  }
  private JRadioButton addRadioButton(String s, ButtonGroup g, JPanel p) {
    JRadioButton button = new JRadioButton(s, false);
    button.addActionListener(this);
    g.add(button);
    p.add(button);
    return button;
  }
  public void actionPerformed(ActionEvent evt) {
    try {
      Object source = evt.getSource();
      if (source == divideByZeroButton) {
        a[1] = a[1] / a[1] - a[1];
      } else if (source == badCastButton) {
        Frame f = (Frame) evt.getSource();
      } else if (source == arrayBoundsButton) {
        a[1] = a[10];
      } else if (source == nullPointerButton) {
        Frame f = null;
        f.setSize(200, 200);
      } else if (source == negSqrtButton) {
        a[1] = Math.sqrt(-1);
      } else if (source == overflowButton) {
        a[1] = 1000 * 1000 * 1000 * 1000;
        int n = (int) a[1];
      } else if (source == noSuchFileButton) {
        FileInputStream is = new FileInputStream("Java Source and Support");
      } else if (source == throwUnknownButton) {
        throw new UnknownError();
      }
    } catch (RuntimeException e) {
      System.out.println("Caught RuntimeException: " + e);
    } catch (Exception e) {
      System.out.println("Caught Exception: " + e);
    }
  }
  public static void main(String[] args) {
    JFrame frame = new ExceptTest();
    frame.setSize(150, 200);
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    frame.show();
  }
}





Finally is always executed

        
// : c09:AlwaysFinally.java
// Finally is always executed.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
class FourException extends Exception {
}
public class AlwaysFinally {
  public static void main(String[] args) {
    System.out.println("Entering first try block");
    try {
      System.out.println("Entering second try block");
      try {
        throw new FourException();
      } finally {
        System.out.println("finally in 2nd try block");
      }
    } catch (FourException e) {
      System.err.println("Caught FourException in 1st try block");
    } finally {
      System.err.println("finally in 1st try block");
    }
  }
} ///:~





Further embellishment of exception classes

        
// : c09:ExtraFeatures.java
// Further embellishment of exception classes.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
class MyException2 extends Exception {
  private int x;
  public MyException2() {
  }
  public MyException2(String msg) {
    super(msg);
  }
  public MyException2(String msg, int x) {
    super(msg);
    this.x = x;
  }
  public int val() {
    return x;
  }
  public String getMessage() {
    return "Detail Message: " + x + " " + super.getMessage();
  }
}
public class ExtraFeatures {
  public static void f() throws MyException2 {
    System.out.println("Throwing MyException2 from f()");
    throw new MyException2();
  }
  public static void g() throws MyException2 {
    System.out.println("Throwing MyException2 from g()");
    throw new MyException2("Originated in g()");
  }
  public static void h() throws MyException2 {
    System.out.println("Throwing MyException2 from h()");
    throw new MyException2("Originated in h()", 47);
  }
  public static void main(String[] args) {
    try {
      f();
    } catch (MyException2 e) {
      e.printStackTrace();
    }
    try {
      g();
    } catch (MyException2 e) {
      e.printStackTrace();
    }
    try {
      h();
    } catch (MyException2 e) {
      e.printStackTrace();
      System.err.println("e.val() = " + e.val());
    }
  }
} ///:~





Get Deepest Throwable

       

/*
 * Copyright (C) 2001-2003 Colin Bell
 * colbell@users.sourceforge.net
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
import java.io.*;
import java.text.NumberFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * General purpose utilities functions.
 *
 * @author 
 */
public class Utilities
{
  public static Throwable getDeepestThrowable(Throwable t)
  {
     Throwable parent = t;
     Throwable child = t.getCause();
     while(null != child)
     {
        parent = child;
        child = parent.getCause();
     }
     return parent;
  }
}





Get the stack trace of the supplied exception.

   
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
 * JBoss DNA (http://www.jboss.org/dna)
 * See the COPYRIGHT.txt file distributed with this work for information
 * regarding copyright ownership.  Some portions may be licensed
 * to Red Hat, Inc. under one or more contributor license agreements.
 * See the AUTHORS.txt file in the distribution for a full listing of 
 * individual contributors.
 *
 * JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
 * is licensed to you under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * JBoss DNA is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
/**
 * Utilities for string processing and manipulation.
 */
public class StringUtil {
  /**
   * Get the stack trace of the supplied exception.
   * 
   * @param throwable the exception for which the stack trace is to be returned
   * @return the stack trace, or null if the supplied exception is null
   */
  public static String getStackTrace( Throwable throwable ) {
      if (throwable == null) return null;
      final ByteArrayOutputStream bas = new ByteArrayOutputStream();
      final PrintWriter pw = new PrintWriter(bas);
      throwable.printStackTrace(pw);
      pw.close();
      return bas.toString();
  }
}





Getting the Stack Trace of an Exception

        

public class Main {
  public static void main(String[] argv) throws Exception {
    try {
      int x = 1, y = 0;
      System.out.println(x / y);
    } catch (Throwable e) {
      StackTraceElement stack[] = e.getStackTrace();
      for (int i = 0; i < stack.length; i++) {
        String filename = stack[i].getFileName();
        if (filename == null) {
          System.out.println("filename is not available");
        }
        String className = stack[i].getClassName();
        System.out.println(className);
        String methodName = stack[i].getMethodName();
        System.out.println(methodName);
        boolean isNativeMethod = stack[i].isNativeMethod();
        System.out.println(isNativeMethod);
        int line = stack[i].getLineNumber();
        System.out.println(line);
      }
    }
  }
}





How an exception can be lost

        
// : c09:LostMessage.java
// How an exception can be lost.
// {ThrowsException}
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
class VeryImportantException extends Exception {
  public String toString() {
    return "A very important exception!";
  }
}
class HoHumException extends Exception {
  public String toString() {
    return "A trivial exception";
  }
}
public class LostMessage {
  void f() throws VeryImportantException {
    throw new VeryImportantException();
  }
  void dispose() throws HoHumException {
    throw new HoHumException();
  }
  public static void main(String[] args) throws Exception {
    LostMessage lm = new LostMessage();
    try {
      lm.f();
    } finally {
      lm.dispose();
    }
  }
} ///:~





Ignoring RuntimeExceptions

        
// : c09:NeverCaught.java
// Ignoring RuntimeExceptions.
// {ThrowsException}
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
public class NeverCaught {
  static void f() {
    throw new RuntimeException("From f()");
  }
  static void g() {
    f();
  }
  public static void main(String[] args) {
    g();
  }
} ///:~





Illustrate various Exceptions

        
import java.util.Date;
import java.util.EmptyStackException;
import java.util.Stack;
public class ExceptionalTest {
  public static void main(String[] args) {
    int count = 1000000;
    Stack s = new Stack();
    System.out.println("Testing for empty stack");
    long s1 = System.currentTimeMillis();
    for (int i = 0; i <= count; i++)
      if (!s.empty())
        s.pop();
    long s2 = System.currentTimeMillis();
    System.out.println((s2 - s1) + " milliseconds");
    System.out.println("Catching EmptyStackException");
    s1 = System.currentTimeMillis();
    for (int i = 0; i <= count; i++) {
      try {
        s.pop();
      } catch (EmptyStackException e) {
      }
    }
    s2 = System.currentTimeMillis();
    System.out.println((s2 - s1) + " milliseconds");
  }
}





Inheriting your own exceptions

        
// : c09:SimpleExceptionDemo.java
// Inheriting your own exceptions.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
class SimpleException extends Exception {
}
public class SimpleExceptionDemo {
  public void f() throws SimpleException {
    System.out.println("Throw SimpleException from f()");
    throw new SimpleException();
  }
  public static void main(String[] args) {
    SimpleExceptionDemo sed = new SimpleExceptionDemo();
    try {
      sed.f();
    } catch (SimpleException e) {
      System.err.println("Caught it!");
    }
  }
} ///:~





Locates a particular type of exception

       
// Copyright 2008 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * Contains static methods useful for manipulating exceptions.
 */
public class ExceptionUtils
{
    /**
     * Locates a particular type of exception, working its way via the cause property of each exception in the exception
     * stack.
     *
     * @param t    the outermost exception
     * @param type the type of exception to search for
     * @return the first exception of the given type, if found, or null
     */
    public static <T extends Throwable> T findCause(Throwable t, Class<T> type)
    {
        Throwable current = t;
        while (current != null)
        {
            if (type.isInstance(current)) return type.cast(current);
            // Not a match, work down.
            current = current.getCause();
        }
        return null;
    }
}





Make a string representation of the exception

       
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Collection;

/**
 * General string utils
 */
public class StringUtils {
  /**
   * Make a string representation of the exception.
   * @param e The exception to stringify
   * @return A string with exception name and call stack.
   */
  public static String stringifyException(Throwable e) {
    StringWriter stm = new StringWriter();
    PrintWriter wrt = new PrintWriter(stm);
    e.printStackTrace(wrt);
    wrt.close();
    return stm.toString();
  }
  
}





Overridden methods may throw only the exceptions

        
// : c09:StormyInning.java
// Overridden methods may throw only the exceptions
// specified in their base-class versions, or exceptions
// derived from the base-class exceptions.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
class BaseballException extends Exception {
}
class Foul extends BaseballException {
}
class Strike extends BaseballException {
}
abstract class Inning {
  public Inning() throws BaseballException {
  }
  public void event() throws BaseballException {
    // Doesn"t actually have to throw anything
  }
  public abstract void atBat() throws Strike, Foul;
  public void walk() {
  } // Throws no checked exceptions
}
class StormException extends Exception {
}
class RainedOut extends StormException {
}
class PopFoul extends Foul {
}
interface Storm {
  public void event() throws RainedOut;
  public void rainHard() throws RainedOut;
}
public class StormyInning extends Inning implements Storm {
  // OK to add new exceptions for constructors, but you
  // must deal with the base constructor exceptions:
  public StormyInning() throws RainedOut, BaseballException {
  }
  public StormyInning(String s) throws Foul, BaseballException {
  }
  // Regular methods must conform to base class:
  //! void walk() throws PopFoul {} //Compile error
  // Interface CANNOT add exceptions to existing
  // methods from the base class:
  //! public void event() throws RainedOut {}
  // If the method doesn"t already exist in the
  // base class, the exception is OK:
  public void rainHard() throws RainedOut {
  }
  // You can choose to not throw any exceptions,
  // even if the base version does:
  public void event() {
  }
  // Overridden methods can throw inherited exceptions:
  public void atBat() throws PopFoul {
  }
  public static void main(String[] args) {
    try {
      StormyInning si = new StormyInning();
      si.atBat();
    } catch (PopFoul e) {
      System.err.println("Pop foul");
    } catch (RainedOut e) {
      System.err.println("Rained out");
    } catch (BaseballException e) {
      System.err.println("Generic baseball exception");
    }
    // Strike not thrown in derived version.
    try {
      // What happens if you upcast?
      Inning i = new StormyInning();
      i.atBat();
      // You must catch the exceptions from the
      // base-class version of the method:
    } catch (Strike e) {
      System.err.println("Strike");
    } catch (Foul e) {
      System.err.println("Foul");
    } catch (RainedOut e) {
      System.err.println("Rained out");
    } catch (BaseballException e) {
      System.err.println("Generic baseball exception");
    }
  }
} ///:~





Print all of the thread"s information and stack traces

      
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.io.PrintWriter;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.lang.reflect.Constructor;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
 * General reflection utils
 */
public class ReflectionUtils {
  private static final Class[] emptyArray = new Class[] {};
  /**
   * Cache of constructors for each class. Pins the classes so they can"t be
   * garbage collected until ReflectionUtils can be collected.
   */
  private static final Map<Class<?>, Constructor<?>> CONSTRUCTOR_CACHE = new ConcurrentHashMap<Class<?>, Constructor<?>>();
  static private ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
  public static void setContentionTracing(boolean val) {
    threadBean.setThreadContentionMonitoringEnabled(val);
  }
  private static String getTaskName(long id, String name) {
    if (name == null) {
      return Long.toString(id);
    }
    return id + " (" + name + ")";
  }
  /**
   * Print all of the thread"s information and stack traces.
   * 
   * @param stream
   *          the stream to
   * @param title
   *          a string title for the stack trace
   */
  public static void printThreadInfo(PrintWriter stream, String title) {
    final int STACK_DEPTH = 20;
    boolean contention = threadBean.isThreadContentionMonitoringEnabled();
    long[] threadIds = threadBean.getAllThreadIds();
    stream.println("Process Thread Dump: " + title);
    stream.println(threadIds.length + " active threads");
    for (long tid : threadIds) {
      ThreadInfo info = threadBean.getThreadInfo(tid, STACK_DEPTH);
      if (info == null) {
        stream.println("  Inactive");
        continue;
      }
      stream.println("Thread " + getTaskName(info.getThreadId(), info.getThreadName()) + ":");
      Thread.State state = info.getThreadState();
      stream.println("  State: " + state);
      stream.println("  Blocked count: " + info.getBlockedCount());
      stream.println("  Waited count: " + info.getWaitedCount());
      if (contention) {
        stream.println("  Blocked time: " + info.getBlockedTime());
        stream.println("  Waited time: " + info.getWaitedTime());
      }
      if (state == Thread.State.WAITING) {
        stream.println("  Waiting on " + info.getLockName());
      } else if (state == Thread.State.BLOCKED) {
        stream.println("  Blocked on " + info.getLockName());
        stream.println("  Blocked by "
            + getTaskName(info.getLockOwnerId(), info.getLockOwnerName()));
      }
      stream.println("  Stack:");
      for (StackTraceElement frame : info.getStackTrace()) {
        stream.println("    " + frame.toString());
      }
    }
    stream.flush();
  }
  private static long previousLogTime = 0;
  /**
   * Return the correctly-typed {@link Class} of the given object.
   * 
   * @param o
   *          object whose correctly-typed <code>Class</code> is to be
   *          obtained
   * @return the correctly typed <code>Class</code> of the given object.
   */
  @SuppressWarnings("unchecked")
  public static <T> Class<T> getClass(T o) {
    return (Class<T>) o.getClass();
  }
  // methods to support testing
  static void clearCache() {
    CONSTRUCTOR_CACHE.clear();
  }
  static int getCacheSize() {
    return CONSTRUCTOR_CACHE.size();
  }
}





Put printStackTrace() into a String: redirect the StackTrace to a String with a StringWriter/PrintWriter

        
import java.io.PrintWriter;
import java.io.StringWriter;
public class Main {
  public static void main(String args[]) {
    try {
      throw new Exception("for no reason!");
    } catch (Exception e) {
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);
      e.printStackTrace(pw);
      System.out.println(sw.toString().toUpperCase());
    }
  }
}





Rethrow a different object from the one that was caught

        
// : c09:RethrowNew.java
// Rethrow a different object from the one that was caught.
// {ThrowsException}
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
class OneException extends Exception {
  public OneException(String s) {
    super(s);
  }
}
class TwoException extends Exception {
  public TwoException(String s) {
    super(s);
  }
}
public class RethrowNew {
  public static void f() throws OneException {
    System.out.println("originating the exception in f()");
    throw new OneException("thrown from f()");
  }
  public static void main(String[] args) throws TwoException {
    try {
      f();
    } catch (OneException e) {
      System.err.println("Caught in main, e.printStackTrace()");
      e.printStackTrace();
      throw new TwoException("from main()");
    }
  }
} ///:~





Return stack trace from the passed exception as a string

      
/*
 * Copyright (C) 2001-2003 Colin Bell
 * colbell@users.sourceforge.net
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
import java.io.*;
import java.text.NumberFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * General purpose utilities functions.
 *
 * @author 
 */
public class Utilities
{

   /**
    * Return the stack trace from the passed exception as a string
    *
    * @param  th  The exception to retrieve stack trace for.
    */
   public static String getStackTrace(Throwable th)
   {
      if (th == null)
      {
         throw new IllegalArgumentException("Throwable == null");
      }
      StringWriter sw = new StringWriter();
      try
      {
         PrintWriter pw = new PrintWriter(sw);
         try
         {
            th.printStackTrace(pw);
            return sw.toString();
         }
         finally
         {
            pw.close();
         }
      }
      finally
      {
         try
         {
            sw.close();
         }
         catch (IOException ex)
         {
           
         }
      }
   }
}





Returns the output of printStackTrace as a String.

       
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.    
 */
/**
 * 
 * 
 * @author 
 * @version $Id: StringUtils.java 685685 2008-08-13 21:43:27Z nbubna $
 */
public class Main {
  /**
   * Returns the output of printStackTrace as a String.
   *
   * @param e A Throwable.
   * @return A String.
   */
  public static final String stackTrace(Throwable e)
  {
      String foo = null;
      try
      {
          // And show the Error Screen.
          ByteArrayOutputStream ostr = new ByteArrayOutputStream();
          e.printStackTrace( new PrintWriter(ostr,true) );
          foo = ostr.toString();
      }
      catch (Exception f)
      {
          // Do nothing.
      }
      return foo;
  }
}





Returns the root cause of an exception

       
/** 
 * 
 * The ObjectStyle Group Software License, version 1.1
 * ObjectStyle Group - http://objectstyle.org/
 * 
 * Copyright (c) 2002-2005, Andrei (Andrus) Adamchik and individual authors
 * of the software. All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 
 * 3. The end-user documentation included with the redistribution, if any,
 *    must include the following acknowlegement:
 *    "This product includes software developed by independent contributors
 *    and hosted on ObjectStyle Group web site (http://objectstyle.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 * 
 * 4. The names "ObjectStyle Group" and "Cayenne" must not be used to endorse
 *    or promote products derived from this software without prior written
 *    permission. For written permission, email
 *    "andrus at objectstyle dot org".
 * 
 * 5. Products derived from this software may not be called "ObjectStyle"
 *    or "Cayenne", nor may "ObjectStyle" or "Cayenne" appear in their
 *    names without prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE OBJECTSTYLE GROUP OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * 
 * This software consists of voluntary contributions made by many
 * individuals and hosted on ObjectStyle Group web site.  For more
 * information on the ObjectStyle Group, please see
 * <http://objectstyle.org/>.
 */
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.Member;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.ruparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
 * Contains various unorganized static utility methods used across Cayenne.
 * 
 * @author Andrei Adamchik
 */
public class Util {
  /**
   * Looks up and returns the root cause of an exception. If none is found, returns
   * supplied Throwable object unchanged. If root is found, recursively "unwraps" it,
   * and returns the result to the user.
   */
  public static Throwable unwindException(Throwable th) {
      if (th instanceof SAXException) {
          SAXException sax = (SAXException) th;
          if (sax.getException() != null) {
              return unwindException(sax.getException());
          }
      }
      else if (th instanceof SQLException) {
          SQLException sql = (SQLException) th;
          if (sql.getNextException() != null) {
              return unwindException(sql.getNextException());
          }
      }
      else if (th.getCause() != null) {
          return unwindException(th.getCause());
      }
      return th;
  }
}





Set the cause of the Exception. Will detect if this is not allowed.

    
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.    
 */
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
/**
 * Use this to create a new Exception.  This will run under JDK 1.3 or greater.
 * However, it running under JDK 1.4 it will set the cause.
 *
 * @author 
 * @since 1.5
 */
public class ExceptionUtils
{
    private static boolean causesAllowed = true;
    /**
     * Create a new RuntimeException, setting the cause if possible.
     * @param message
     * @param cause
     * @return A runtime exception object.
     */
    public static RuntimeException createRuntimeException(
            String message, Throwable cause)
    {
        return (RuntimeException) createWithCause(
                RuntimeException.class, message, cause);
    }
    /**
     * Create a new Exception, setting the cause if possible.
     * @param clazz
     * @param message
     * @param cause
     * @return A Throwable.
     */
    public static Throwable createWithCause(Class clazz,
            String message, Throwable cause)
    {
        Throwable re = null;
        if (causesAllowed)
        {
            try
            {
                Constructor constructor = clazz
                        .getConstructor(new Class[]{String.class,
                                Throwable.class});
                re = (Throwable) constructor
                        .newInstance(new Object[]{message, cause});
            }
            catch (RuntimeException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                causesAllowed = false;
            }
        }
        if (re == null)
        {
            try
            {
                Constructor constructor = clazz
                        .getConstructor(new Class[]{String.class});
                re = (Throwable) constructor
                        .newInstance(new Object[]{message
                                + " caused by " + cause});
            }
            catch (RuntimeException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw new RuntimeException("Error caused " + e); // should be impossible
            }
        }
        return re;
    }
    /**
     * Set the cause of the Exception.  Will detect if this is not allowed.
     * @param onObject
     * @param cause
     */
    public static void setCause(Throwable onObject, Throwable cause)
    {
        if (causesAllowed)
        {
            try
            {
                Method method = onObject.getClass().getMethod("initCause", new Class[]{Throwable.class});
                method.invoke(onObject, new Object[]{cause});
            }
            catch (RuntimeException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                causesAllowed = false;
            }
        }
    }
}





Simple demo of exceptions

        
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */

/** Simple demo of exceptions */
public class ExceptionDemo {
  public static void main(String[] argv) {
    new ExceptionDemo().doTheWork();
  }
  /** This method demonstrates calling a method that might throw
   * an exception, and catching the resulting exception.
   */
  public void doTheWork() {
    Object o = null;
    for (int i=0; i<5; i++) {
      try {
        o = makeObj(i);
      } catch (IllegalArgumentException e) {
        System.err.println("Error: (" + e.getMessage() + ").");
        return;    // cut off println below if makeObj failed.
      }
      System.out.println(o);  // process the created object in some way
    }
  }
  /** Model of a method that creates and returns an object.
   * This method is really here to show how you throw exceptions.
   * @exception  IllegalArgumentException  if called with value 1.
   */
  public Object makeObj(int type) throws IllegalArgumentException {
    if (type == 1)  // detects an error...
      throw new IllegalArgumentException("Don"t like type " + type);
    return new Object();
  }
}





Simple demo of exceptions, with finally clause

        
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */

/** Simple demo of exceptions, with finally clause */
public class ExceptionDemo2 {
  public static void main(String[] argv) {
    new ExceptionDemo2().doTheWork();
  }
  /** This method demonstrates calling a method that might throw
   * an exception, and catching the resulting exception.
   */
  public void doTheWork() {
    Object o = null;
    for (int i=0; i<5; i++) {
      try {
        o = makeObj(i);
      } catch (IllegalArgumentException e) {
        System.err.println("Error: (" + e.getMessage() + ").");
        return;    // cut off println below if makeObj failed.
      } finally {
        System.err.println("All done");
        if (o==null)
          System.exit(0);
      }
      System.out.println(o);  // process the created object in some way
    }
  }
  /** Model of a method that creates and returns an object.
   * This method is really here to show how you throw exceptions.
   * @exception  IllegalArgumentException  if called with value 1.
   */
  public Object makeObj(int type) throws IllegalArgumentException {
    if (type == 1)  // detects an error...
      throw new IllegalArgumentException("Don"t like type " + type);
    return new Object();
  }
}





StackTrace

        
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */

/**
 * Every "Exception" (or subclass) object contains a "stackTrace", or
 * traceback, meant to indicate where the error occurred.
 *
 * Let"s find out where a stackTrace comes from, and how to use it, when
 * exceptions are created and thrown. Some textbooks claim that it is
 * the operation of constructing the exception that anchors its trace,
 * others the throwing. Let us see for ourselves.
 */
public class StackTrace {
  IllegalArgumentException ex;
  public static void main(String[] argv) {
    StackTrace st = new StackTrace();
    st.makeit();
    System.out.println("CONSTRUCTED BUT NOT THROWN");
    st.ex.printStackTrace();  
    st.throwit();
    // MAY BE NOTREACHED - THINK ABOUT IT!
    System.out.println("CONSTRUCTED BUT NOT THROWN");
    st.ex.printStackTrace();
  }
  public void makeit() {
    ex = new IllegalArgumentException("Don"t like the weather today");
  }
  public void throwit() throws IllegalArgumentException {
    throw ex;
  }
}





The finally clause is always executed

        
// : c09:FinallyWorks.java
// The finally clause is always executed.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
class ThreeException extends Exception {
}
public class FinallyWorks {
  static int count = 0;
  public static void main(String[] args) {
    while (true) {
      try {
        // Post-increment is zero first time:
        if (count++ == 0)
          throw new ThreeException();
        System.out.println("No exception");
      } catch (ThreeException e) {
        System.err.println("ThreeException");
      } finally {
        System.err.println("In finally clause");
        if (count == 2)
          break; // out of "while"
      }
    }
  }
} ///:~





ThreadBasedCatcher - Demonstrate catching uncaught exceptions

        
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
 * ThreadBasedCatcher - Demonstrate catching uncaught exceptions 
 * thrown in an unrelated Thread.
 * @author ian
 * @verion $Id: ThreadBasedCatcher.java,v 1.2 2004/03/20 20:43:27 ian Exp $
 */
public class ThreadBasedCatcher extends JFrame{
  public static void main(String[] args) {
    new ThreadBasedCatcher().setVisible(true);
  }
  public ThreadBasedCatcher(){
    Container cp = getContentPane();
    JButton crasher = new JButton("Crash");
    cp.add(crasher);
    crasher.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){
        throw new RuntimeException("You asked for it");
      }
    });
    Thread.setDefaultUncaughtExceptionHandler(
        new Thread.UncaughtExceptionHandler(){
          public void uncaughtException(Thread t, Throwable ex){
            System.out.println(
              "You crashed thread " + t.getName());
            System.out.println(
              "Exception was: " + ex.toString());
          }
        });
    pack();
  }
}





Throw Exception Out

        
// : c09:ThrowOut.java
// {ThrowsException}
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
public class ThrowOut {
  public static void main(String[] args) throws Throwable {
    try {
      throw new Throwable();
    } catch (Exception e) {
      System.err.println("Caught in main()");
    }
  }
} ///:~





Turning off Checked exceptions

        
//: c09:TurnOffChecking.java
// "Turning off" Checked exceptions.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.io.*;
class WrapCheckedException {
  void throwRuntimeException(int type) {
    try {
      switch(type) {
        case 0: throw new FileNotFoundException();
        case 1: throw new IOException();
        case 2: throw new RuntimeException("Where am I?");
        default: return;
      }
    } catch(Exception e) { // Adapt to unchecked:
      throw new RuntimeException(e);
    }
  }
}
class SomeOtherException extends Exception {}
public class TurnOffChecking {
  public static void main(String[] args) {
  
    WrapCheckedException wce = new WrapCheckedException();
    // You can call f() without a try block, and let
    // RuntimeExceptions go out of the method:
    wce.throwRuntimeException(3);
    // Or you can choose to catch exceptions:
    for(int i = 0; i < 4; i++)
      try {
        if(i < 3)
          wce.throwRuntimeException(i);
        else
          throw new SomeOtherException();
      } catch(SomeOtherException e) {
          System.out.println("SomeOtherException: " + e);
      } catch(RuntimeException re) {
        try {
          throw re.getCause();
        } catch(FileNotFoundException e) {
          System.out.println(
            "FileNotFoundException: " + e);
        } catch(IOException e) {
          System.out.println("IOException: " + e);
        } catch(Throwable e) {
          System.out.println("Throwable: " + e);
        }
      }
  }
} ///:~





Utility class to work with throwables

       
/*
 * Copyright 2006-2007 The Scriptella Project Team.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.sql.SQLException;
/**
 * Utility class to work with throwables.
 *
 * @author Fyodor Kupolov
 * @version 1.0
 */
public final class ExceptionUtils {
    private ExceptionUtils() {
    }
    /**
     * This method checks if throwable has {@link Throwable#getCause() cause}.
     * If cause==null, this method tries to obtain cause based on throwable type,
     * e.g. {@link java.sql.SQLException#getNextException()}
     *
     * @param throwable throwable to find cause.
     * @return cause of throwable.
     */
    public static Throwable getCause(Throwable throwable) {
        if (throwable.getCause() != null) {
            return throwable.getCause();
        }
        if (throwable instanceof SQLException) {
            return ((SQLException) throwable).getNextException();
        }
        return null;
    }
    /**
     * This method throws unchecked throwable, i.e. {@link Error} or {@link RuntimeException}.
     *
     * @param unchecked unchecked throwable.
     */
    public static void throwUnchecked(Throwable unchecked) {
        if (unchecked instanceof Error) {
            throw (Error) unchecked;
        }
        if (unchecked instanceof RuntimeException) {
            throw (RuntimeException) unchecked;
        }
        throw new IllegalStateException("Unchecked throwable expected but was " + unchecked.getClass(), unchecked);
    }
    /**
     * Utility method to ignore non important exceptions.
     * @param throwable throwable to ignore.
     */
    public static void ignoreThrowable(Throwable throwable) {
    }
}





Utility methods for dealing with stack traces

       
/**************************************************************************************
 * Copyright (c) Jonas Bon�r, Alexandre Vasseur. All rights reserved.                 *
 * http://aspectwerkz.codehaus.org                                                    *
 * ---------------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the LGPL license      *
 * a copy of which has been included with this distribution in the license.txt file.  *
 **************************************************************************************/
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
/**
 * Utility methods for dealing with stack traces.
 *
 * @author 
 */
public final class StackTraceHelper {
    /**
     * Removes the AspectWerkz specific elements from the stack trace.
     *
     * @param exception the Throwable to modify the stack trace on
     * @param className the name of the fake origin class of the exception
     */
    public static void hideFrameworkSpecificStackTrace(final Throwable exception, final String className) {
        if (exception == null) {
            throw new IllegalArgumentException("exception can not be null");
        }
        if (className == null) {
            throw new IllegalArgumentException("class name can not be null");
        }
        final List newStackTraceList = new ArrayList();
        final StackTraceElement[] stackTrace = exception.getStackTrace();
        int i;
        for (i = 1; i < stackTrace.length; i++) {
            if (stackTrace[i].getClassName().equals(className)) {
                break;
            }
        }
        for (int j = i; j < stackTrace.length; j++) {
            newStackTraceList.add(stackTrace[j]);
        }
        final StackTraceElement[] newStackTrace = new StackTraceElement[newStackTraceList.size()];
        int k = 0;
        for (Iterator it = newStackTraceList.iterator(); it.hasNext(); k++) {
            final StackTraceElement element = (StackTraceElement) it.next();
            newStackTrace[k] = element;
        }
        exception.setStackTrace(newStackTrace);
    }
}





What happens if a method declares an unchecked exception?

        
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */

/** What happens if a method declares an unchecked exception?
 * Some people seem to think that declaring a method in a throws
 * clause is what makes it "checked". As we see here, this is not
 * the case; checked-ness has only to do with an exception"s place
 * in Java"s class inheritance hierarchy.
 */
public class ThrowsUnchecked {
  public static void main(String[] argv) {
    new ThrowsUnchecked().doTheWork();
  }
  /** This method demonstrates calling a method that might throw
   * an exception, and catching the resulting exception.
   */
  public void doTheWork() {
    String s = " 42";
    int i = testit(s);  // Note: compiles with no try/catch.
    System.out.println("parseit(" + s + ") returned " + i);
  }
  /** Model of a method that might throw an unchecked exception.
   * @exception  NumberFormatException  if called with value 1.
   */
  public int testit(String input) throws NumberFormatException {
    return Integer.parseInt(input);
  }
}





Your own Exception class

        
// : c09:FullConstructors.java
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
class MyException extends Exception {
  public MyException() {
  }
  public MyException(String msg) {
    super(msg);
  }
}
public class FullConstructors {
  public static void f() throws MyException {
    System.out.println("Throwing MyException from f()");
    throw new MyException();
  }
  public static void g() throws MyException {
    System.out.println("Throwing MyException from g()");
    throw new MyException("Originated in g()");
  }
  public static void main(String[] args) {
    try {
      f();
    } catch (MyException e) {
      e.printStackTrace();
    }
    try {
      g();
    } catch (MyException e) {
      e.printStackTrace();
    }
  }
} ///:~