Java Tutorial/Development/Exception — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 17:44, 31 мая 2010

Check whether given exception is compatible with the exceptions declared in a throws clause

import java.lang.reflect.Array;
import java.util.Arrays;
/*
 * Copyright 2002-2007 the original author or authors.
 *
 * 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.
 */
//Revised from springframework
/**
 * Miscellaneous object utility methods. Mainly for internal use within the
 * framework; consider Jakarta"s Commons Lang for a more comprehensive suite
 * of object utilities.
 *
 * @author Juergen Hoeller
 * @author Keith Donald
 * @author Rod Johnson
 * @author Rob Harrop
 * @author Alex Ruiz
 * @since 19.03.2004
 * @see org.apache.rumons.lang.ObjectUtils
 */
abstract class ObjectUtils {
  private static final int INITIAL_HASH = 7;
  private static final int MULTIPLIER = 31;
  private static final String EMPTY_STRING = "";
  private static final String NULL_STRING = "null";
  private static final String ARRAY_START = "{";
  private static final String ARRAY_END = "}";
  private static final String EMPTY_ARRAY = ARRAY_START + ARRAY_END;
  private static final String ARRAY_ELEMENT_SEPARATOR = ", ";

  /**
   * Check whether the given exception is compatible with the exceptions
   * declared in a throws clause.
   * @param ex the exception to checked
   * @param declaredExceptions the exceptions declared in the throws clause
   * @return whether the given exception is compatible
   */
  public static boolean isCompatibleWithThrowsClause(Throwable ex, Class[] declaredExceptions) {
    if (!isCheckedException(ex)) {
      return true;
    }
    if (declaredExceptions != null) {
      for (int i = 0; i < declaredExceptions.length; i++) {
        if (declaredExceptions[i].isAssignableFrom(ex.getClass())) {
          return true;
        }
      }
    }
    return false;
  }
  /**
   * Return whether the given throwable is a checked exception:
   * that is, neither a RuntimeException nor an Error.
   * @param ex the throwable to check
   * @return whether the throwable is a checked exception
   * @see java.lang.Exception
   * @see java.lang.RuntimeException
   * @see java.lang.Error
   */
  public static boolean isCheckedException(Throwable ex) {
    return !(ex instanceof RuntimeException || ex instanceof Error);
  }
}





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;
            }
        }
    }
}





Defining Your Own Exceptions, Throwing Your Own Exception

class DreadfulProblemException extends ArithmeticException {
  public DreadfulProblemException() {
  }
  public DreadfulProblemException(String s) {
    super(s); 
  }
}
public class MainClass{
  public static void main(String[] a){
    int[] array = new int[]{1,0,2};
    int index = 0;
    try {
      System.out.println("First try block in divide() entered");
      array[index + 2] = array[index]/array[index + 1];
      System.out.println("Code at end of first try block in divide()");
    } catch(ArithmeticException e) {
      System.out.println("Arithmetic exception caught in divide()");
      throw new DreadfulProblemException("index + 1");    // Throw new exception
    } catch(ArrayIndexOutOfBoundsException e) {
      System.out.println(
                  "Index-out-of-bounds index exception caught in divide()");
    }
    System.out.println("Executing code after try block in divide()");
  }
}



First try block in divide() entered
Arithmetic exception caught in divide()
Exception in thread "main" DreadfulProblemException: index + 1
  at MainClass.main(MainClass.java:20)


Demonstrate exception chaining.

class ChainExcDemo {
  static void demoproc() {
    NullPointerException e = new NullPointerException("top layer");
    e.initCause(new ArithmeticException("cause"));
    throw e;
  }
  public static void main(String args[]) {
    try {
      demoproc();
    } catch (NullPointerException e) {
      System.out.println("Caught: " + e);
      System.out.println("Original cause: " + e.getCause());
    }
  }
}





Error Handling

  1. You can isolate code that may cause a runtime error using the try statement.
  2. try statement normally is accompanied by the catch and the finally statements.
  3. In case of an error, Java stops the processing of the try block and jump to the catch block.
  4. In the catch block, you can handle the error or notify the user by "throwing" a java.lang.Exception object. Or you can re-throw the exception or a new Exception object back to the code that called the method.
  5. If a thrown exception is not caught, the application will stop abruptly.
  6. In the finally block, you write code that will be run whether or not an error has occurred.
  7. The finally block is optional.
  8. You can have more than one catch block. This is because the code can throw different types of exceptions.
  9. If the type of exception thrown does not match the exception type in the first catch block, the JVM goes to the next catch block and does the same thing until it finds a match.
  10. If no match is found, the exception object will be thrown to the method caller.
  11. If the caller does not put the offending code that calls the method in a try block, the program crashes.

This is the syntax of the try statement.



try {
         [code that may throw an exception]
     } catch (ExceptionType-1 e) {
         [code that is executed when ExceptionType-1 is thrown]
     } [catch (ExceptionType-2 e) {
         [code that is executed when ExceptionType-2 is thrown]
     }]
       ...
     } [catch (ExceptionType-n e) {
         [code that is executed when ExceptionType-n is thrown]
     }]
     [finally {
         [code that runs regardless of whether an exception was thrown]]
     }]





Exception Objects: stack trace

public class MainClass {
  public static void main(String[] args) {
    int[] array = new int[]{1,0,2};
    int index = 0;
    try {
      System.out.println("\nFirst try block in divide() entered");
      array[index + 2] = array[index]/array[index + 1];
      System.out.println("Code at end of first try block in divide()");
    } catch(ArithmeticException e) {
      System.err.println("Arithmetic exception caught in divide()\n" +
                         "\nMessage in exception object:\n\t" +
                          e.getMessage());
      System.err.println("\nStack trace output:\n");
      e.printStackTrace();
      System.err.println("\nEnd of stack trace output\n");
    } catch(ArrayIndexOutOfBoundsException e) {
      System.err.println("Index-out-of-bounds exception caught in divide()\n" +
                         "\nMessage in exception object:\n\t" + e.getMessage());
      System.err.println("\nStack trace output:\n");
      e.printStackTrace();
      System.out.println("\nEnd of stack trace output\n");
    } finally {
      System.err.println("finally clause in divide()");
    }
    System.out.println("Executing code after try block in divide()");
  }
}



First try block in divide() entered
Executing code after try block in divide()Arithmetic exception caught in divide()
Message in exception object:
  / by zero
Stack trace output:
java.lang.ArithmeticException: / by zero
  at MainClass.main(MainClass.java:8)
End of stack trace output
finally clause in divide()


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);
      }
    }
  }
}





Handling Exceptions

public class MainClass {
  public static void main(String[] args) {
    int i = 1;
    int j = 0;
    try {
      System.out.println("Try block entered " + "i = " + i + "j = " + j);
      System.out.println(i / j); // Divide by 0 - exception thrown
      System.out.println("Ending try block");
    } catch (ArithmeticException e) { // Catch the exception
      System.out.println("Arithmetic exception caught");
    }
    System.out.println("After try block");
    return;
  }
}



Try block entered i = 1j = 0
Arithmetic exception caught
After try block


Is Checked Exception

import java.lang.reflect.Array;
import java.util.Arrays;
/*
 * Copyright 2002-2007 the original author or authors.
 *
 * 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.
 */
//Revised from springframework
/**
 * Miscellaneous object utility methods. Mainly for internal use within the
 * framework; consider Jakarta"s Commons Lang for a more comprehensive suite
 * of object utilities.
 *
 * @author Juergen Hoeller
 * @author Keith Donald
 * @author Rod Johnson
 * @author Rob Harrop
 * @author Alex Ruiz
 * @since 19.03.2004
 * @see org.apache.rumons.lang.ObjectUtils
 */
abstract class ObjectUtils {
  private static final int INITIAL_HASH = 7;
  private static final int MULTIPLIER = 31;
  private static final String EMPTY_STRING = "";
  private static final String NULL_STRING = "null";
  private static final String ARRAY_START = "{";
  private static final String ARRAY_END = "}";
  private static final String EMPTY_ARRAY = ARRAY_START + ARRAY_END;
  private static final String ARRAY_ELEMENT_SEPARATOR = ", ";

  /**
   * Return whether the given throwable is a checked exception:
   * that is, neither a RuntimeException nor an Error.
   * @param ex the throwable to check
   * @return whether the throwable is a checked exception
   * @see java.lang.Exception
   * @see java.lang.RuntimeException
   * @see java.lang.Error
   */
  public static boolean isCheckedException(Throwable ex) {
    return !(ex instanceof RuntimeException || ex instanceof Error);
  }
}





Java"s Checked Exceptions Defined in java.lang

Exception                          Meaning
ClassNotFoundException             Class not found.
CloneNotSupportedException         Attempt to clone an object that does not implement the Cloneable interface.
IllegalAccessException             Access to a class is denied.
InstantiationException             Attempt to create an object of an abstract class or interface.
InterruptedException               One thread has been interrupted by another thread.
NoSuchFieldException               A requested field does not exist.
NoSuchMethodException              A requested method does not exist.





Java"s Unchecked RuntimeException Subclasses

Exception                         Meaning
ArithmeticException               Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException    Array index is out-of-bounds.
ArrayStoreException               Assignment to an array element of an incompatible type.
ClassCastException                Invalid cast.
IllegalArgumentException          Illegal argument used to invoke a method.
IllegalMonitorStateException      Illegal monitor operation, such as waiting on an unlocked thread.
IllegalStateException             Environment or application is in incorrect state.
IllegalThreadStateException       Requested operation not compatible with current thread state.
IndexOutOfBoundsException         Some type of index is out-of-bounds.
NegativeArraySizeException        Array created with a negative size.
NullPointerException              Invalid use of a null reference.
NumberFormatException             Invalid conversion of a string to a numeric format.
SecurityException                 Attempt to violate security.
StringIndexOutOfBounds            Attempt to index outside the bounds of a string.
TypeNotPresentException           Type not found. (Added by J2SE 5.)
UnsupportedOperationException     An unsupported operation was encountered.





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();
  }
  
}





Multiple catch Blocks

public class MainClass {
  public static void main(String[] args) {
    int[] x = { 10, 5, 0 };
    try {
      System.out.println("First try block in main() entered");
      divide(x, 0);
      x[1] = 0;
      divide(x, 0);
      x[1] = 1;
      divide(x, 1);
    } catch (ArithmeticException e) {
      System.out.println("Arithmetic exception caught in main()");
    } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("Index-out-of-bounds exception caught in main()");
    }
  }
  private static void divide(int[] intArray, int j) {
    for (int i : intArray) {
      System.out.println(i);
      System.out.println(j);
      System.out.println(i / j);
      System.out.println();
    }
  }
}



First try block in main() entered
10
0
Arithmetic exception caught in main()


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());
    }
  }
}





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;
  }
}





The finally Block

A finally block is always executed, regardless of whether or not exceptions are thrown.



import java.io.IOException;
public class MainClass {
  public static void main(String[] args) {
    try {
      System.out.println("In second try block in main()");
      System.in.read();
      return;
    } catch (IOException e) {
      System.out.println("I/O exception caught in main()");
    } finally {
      System.out.println("finally block for second try block in main()");
    }
    System.out.println("Code after second try block in main()");
  }
}



In second try block in main()
finally block for second try block in main()


This program creates a custom exception type.

class MyException extends Exception {
  private int detail;
  MyException(int a) {
    detail = a;
  }
  public String toString() {
    return "MyException[" + detail + "]";
  }
}
class ExceptionDemo {
  static void compute(int a) throws MyException {
    System.out.println("Called compute(" + a + ")");
    if (a > 10)
      throw new MyException(a);
    System.out.println("Normal exit");
  }
  public static void main(String args[]) {
    try {
      compute(1);
      compute(20);
    } catch (MyException e) {
      System.out.println("Caught " + e);
    }
  }
}





Throwing an Exception from a Method

  1. Most of the time a try block is accompanied by a catch block that catches the java.lang.Exception in addition to other catch blocks.
  2. The order of the catch blocks is important.
  3. The more specific exception type appears first.



public class MainClass {
  public static void main(String[] args) {
    String input = null;
    try {
      String capitalized = capitalize(input);
      System.out.println(capitalized);
    } catch (NullPointerException e) {
      System.out.println(e.toString());
    }
  }
  public static String capitalize(String s) throws NullPointerException {
    if (s == null) {
      throw new NullPointerException("Your passed a null argument");
    }
    Character firstChar = s.charAt(0);
    String theRest = s.substring(1);
    return firstChar.toString().toUpperCase() + theRest;
  }
}





Types of Exceptions

  1. An exception is an object of the subclass of class Throwable.
  2. Class Error and the class Exception cover all the standard exceptions.


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);
    }
}





Write a catch block that handles java.lang.Exception

All Java exception classes derive from the java.lang.Exception class. When a method throws multiple exceptions, rather than catch all the exceptions, you can simply write a catch block that handles java.lang.Exception:



public class MainClass {
  public static void main(String[] args) {
    String input = null;
    try {
      String capitalized = capitalize(input);
      System.out.println(capitalized);
    } catch (Exception e) {
      System.out.println(e.toString());
    }  
  }
  static String capitalize(String s) throws NullPointerException, AlreadyCapitalizedException {
    if (s == null) {
      throw new NullPointerException("Your passed a null argument");
    }
    Character firstChar = s.charAt(0);
    if (Character.isUpperCase(firstChar)) {
      throw new AlreadyCapitalizedException();
    }
    String theRest = s.substring(1);
    return firstChar.toString().toUpperCase() + theRest;
  }
}
class AlreadyCapitalizedException extends Exception {
  public String toString() {
    return "Input has already been capitalized";
  }
}