Java. Сlasses for handling exceptions from the java.lang package. Methods of Throwable class. Examples




Java classes for handling exceptions from the java.lang package. Methods of Throwable class. Examples


Contents


Search other websites:

1. Exception types supported by the Java exception system

Java has developed an efficient exception handling mechanism. The basis of this mechanism are classes forming a hierarchy. For all Java exception classes, the base class is the Throwable class.

Two main classes are inherited from the Throwable class:

  • Exception – designed to specify exceptional conditions that are intercepted by the program. If you need to declare your own class (type) of exceptions, then this class can be inherited from the Exception class;
  • Error – a class that is designed to describe exceptions (errors) that occur in the Java environment itself. Such exceptions are not specified during the normal execution of the application program. Examples of system errors: insufficient memory, stack overflow.

The top level diagram of the Java class hierarchy is shown in the figure.

The top of the hierarchy of Java exception classes

Figure. The top of the hierarchy of Java exception classes

 

2. Classification of exceptions on the basis of the presence in the throws statement. Unchecked exceptions. Checked Exceptions

As you know, a method can throw exceptions that can be caught in other methods of higher levels. In this case, the method should indicate the list of processed exceptions in the throws statement.

More details about the operation of the throws operator are described in the topic:

If the type of the generated exception is a subclass of the standard RuntimeException class, then it is not necessary to indicate this type in the list of the throws operator of the method. Such an exception is called an unchecked exception. In this case, the compiler does not check whether such exceptions are processed or generated at some location in the program.

If the type of the generated exception is not a subclass of the standard RuntimeException class, then this exception is called the checked exception. If this type of exception is thrown, it must be included in the throws statement.

 

3. List of subclasses of unchecked exceptions from java.lang package

Among the wide variety of classes and interfaces, the java.lang package contains a powerful arsenal of classes for handling exceptions. These classes and interfaces form the basis of all Java programs. The java.lang package is automatically imported into all programs.

The following is a list of subclasses of unchecked exceptions derived from the RuntimeException class and which are defined in the java.lang package:

  • ArithmeticException – arithmetic error (for example, division by zero);
  • ArrayIndexOutOfBoundsException – index outside the array;
  • ArrayStoreException – assignment to an array element of an object of an incompatible type;
  • ClassCastException – wrong type conversion;
  • EnumConstantNotPresent – an attempt to use an undefined enumeration value;
  • IllegalArgumentException – invalid argument when calling a method;
  • IllegalMonitorStateException – invalid control operation;
  • IllegalStateException – invalid state of the environment or application;
  • IllegalThreadStateException – incompatibility of the requested operation with the current state of the thread;
  • IndexOutOfBoundsException – exit of an index of some type beyond acceptable boundaries;
  • NegativeArraySizeException – creating an array of negative size;
  • NullPointerException – incorrect use of an empty reference;
  • NumberFormatException – incorrect conversion of a character string to a number format;
  • SecurityException – an attempt to violate security;
  • StringIndexOutOfBounds – an attempt to access by index outside the character string;
  • TypeNotPresentException – type not found;
  • UnsupportedOperationException – an unsupported operation was found.

 

4. Checked exceptions from java.lang package

If the type of the generated exception is not a subclass of the standard RuntimeException class, then this exception is called the checked exception. If this type of exception is thrown, it must be included in the throws statement of the method.

In Java, the java.lang package implements a number of checked exceptions. Below is a list of them:

  • ClassNotFoundException – the class was not found;
  • CloneNotSupportedException – an attempt to clone an object from a class that does not implement the Cloneable interface;
  • IllegalAccessException – access to the class is denied;
  • InstantiationException – an attempt to create an object of an abstract class or interface;
  • InterruptedException – one thread of execution is interrupted by another thread;
  • NoSuchFieldException – the requested field does not exist;
  • NoSuchMethodException – the requested method does not exist;
  • ReflectiveOperationException – superclass of exceptions related to reflection.

Also, it is imperative that you include in your throws operator’s exclusion list your own exception classes to test them.



 

5. What is the purpose of the Throwable class? Methods of Throwable class.

The Throwable class is the base class for all standard Java exception classes. This class provides a number of methods that you can use or override in your own exception handling classes. These classes must be inherited from the Exception class, which is inherited from the Throwable class (see the figure). The Exception class contains no methods.

The following is a list of Throwable class methods.

1. Method

final void addSuppressed(Throwable exception)

Adds the specified exception to the list of suppressed exceptions. This list is associated with the caller exception. The method is used for use in a try statement with resources.

  1. Method
Throwable fillInStackTrace()

returns an object of the Throwable class containing the full stack trace. This object can be regenerated.

3. Method

Throwable getCause()

It returns an exception that underlies the current exception. The method returns null if there is no such exception. This method is used when creating exception chains – it raises an exception that raises the current exception.

4. Method

String getLocalizedMessage()

returns a localized description of the exception.

5. Method

String getMessage()

returns a description of the exception.

6. Method

StackTraceElement[] getStackTrace()

returns an array containing the elementwise trace of the stack as objects of the StackTraceElement class.

7. Method

final Throwable[] getSuppressed()

receives suppressed exceptions related to the causing exception, and returns an array that contains the result. Suppressed exceptions are thrown in a statement try with resources.

8. Method

Throwable initCause(Throwable exception_cause)

associates the input parameter exception_cause with the causing exception, specifying it as the cause of this causing exception. It returns a reference to the exception. The method is used when creating exception chains.

9. Method

void printStackTrace();

displays the stack trace.

10. Method printStackTrace()has two more overloaded implementations

void printStackTrace(PrintStream output_stream)
void printStackTrace(PrintWriter output_stream)

The method routes the stack trace to the specified output_stream.

11. Method

void setStackTrace(StackTraceElement elements[])

sets the stack trace for the given elements.

12. Method

String toString()

returns an object of type String containing the description of the exception. This method can be called from the println() method when outputting an object of type Throwable.

 






6. An example of using some methods of the Throwable class. Developing your own exception class

The example demonstrates the use of some methods of the Throwable class:

  • getLocalizedMessage();
  • getMessage();
  • toString();
  • getStackTrace();
  • fillInStackTrace().

The class MyException is inherited from the class Exception is declared. In the hierarchy of Java exception classes, the Exception class is inherited from the Throwable class. Therefore, the MyException class can use and override the methods of the Throwable class.

The text of the program is as follows:

import java.util.Scanner;

// own exception class, inherited from Exception
class MyException extends Exception
{
  // overridden getLocalizedMessage() function
  public String getLocalizedMessage()
  {
    return "MyException.getLocalizedMessage()";
  }
}

// class containing main() function
public class Train04 {
  // The main() function tests the operation of the MyException class
  public static void main(String[] args) {
    // Input the number x. If the number is outside [0..100],
    // then gentrate exception MyException
    int x;
    Scanner sc = new Scanner(System.in);
    System.out.print("x = ");
    x = sc.nextInt(); // input x

    try {
      // generate an exception (create the object of type MyException),
      // if x is outside [0..100]
      if ((x<0)||(x>100))
        throw new MyException();
      System.out.println("OK!");
    }
    catch(MyException e)
    {
      // handling an exception of type MyException,
      // demonstration of some methods of the class Throwable
      System.out.println("Return from getLocalizedMessage(): " + e.getLocalizedMessage());
      System.out.println("Return from getMessage(): " + e.getMessage());
      System.out.println("Method printStackTrace(): ");
      e.printStackTrace();
      System.out.println("Method toString(): " + e.toString());
      System.out.println("------------------------");
      System.out.println("Method getStackTrace(). Stack trace: ");
      StackTraceElement[] stE;
      stE = e.getStackTrace(); // метод getStackTrace()

      for (int i=0;i<stE.length;i++)
        System.out.println(stE[i].toString());
      System.out.println("-------------------------");

      System.out.println("Method fillStackTrace(). Stack trace: ");
      Throwable tA = e.fillInStackTrace();
      StackTraceElement[] stE2 = tA.getStackTrace();

      for (int i=0; i<stE2.length; i++)
        System.out.println(stE[i].toString());
      System.out.println("-------------------------");
    }
  }
}

Let’s explain some code snippets.

For purposes of demonstration, the getLocalizedMessage() method is overridden in the MyException class. When this method is called, a message from this overridden method is displayed. Using this example, you can override other methods of the Throwable class.

The main() function demonstrates the use of Throwable class methods. The variable x is introduced, which is checked for valid values in the range of 0 to 100. If x is less than 0 or greater than 100, an exception of type MyException is thrown.

The result of the program

x = 200
Return from getLocalizedMessage(): MyException.getLocalizedMessage()
Return from getMessage(): null
Method printStackTrace():
Method toString(): MyException: MyException.getLocalizedMessage()
------------------------
Method getStackTrace(). Stack trace:
Train04.main(Train04.java:36)
-------------------------
Method fillStackTrace(). Stack trace:
Train04.main(Train04.java:36)
-------------------------
MyException: MyException.getLocalizedMessage()

 


Related topics