Methods in Throwable, Java’s Built-in Exceptions, and Custom Exception

Methods in Throwable Class

Till now we are just catching exceptions but not using methods of Throwable class for better handling of an exception. Throwable has a number of methods which can be used to handle or display useful information regarding exception occurred. Below are the list of methods and their description.

Method Description
Throwable fillInStackTrace() This method returns a Throwable object with complete details of the exception.
String getLocalizedMessage( ) Returns localized information of the exception.
String getMessage( ) Returns a information of the exception.
void printStackTrace( ) Displays the stack trace.
void printStackTrace(PrintStream stream) Sends the stack trace to the specified stream.
void printStackTrace(PrintWriter stream) Sends the stack trace to the specified stream.
String toString( ) Returns a String object containing a complete description of the exception. This method is called by println to display information.

Below example demonstrates some of these methods, in general, we use printStackTrace method more to understand where is the problem in a source code.

/*
This is a simple Java program about Exception Handling.
Call this file KH_Throwable.java.
*/

class ExcTest {
	static void genException() {
		int nums[] = new int[4];
		System.out.println("Before exception is generated.");
		nums[7] = 10;
		System.out.println("this won't be displayed");
	}
}
class KH_Throwable {
	
	public static void main(String args[]) {
		try {
			ExcTest.genException();
		}
		catch (ArrayIndexOutOfBoundsException exc) {
			System.out.println("Standard message is: ");
			System.out.println(exc);
			System.out.println("\nStack trace: ");
			exc.printStackTrace();
		}
		System.out.println("After catch statement.");
	}
}

Download the code  Run the code

Output:

Before exception is generated.
Standard message is:
java.lang.ArrayIndexOutOfBoundsException: 7

Stack trace:
java.lang.ArrayIndexOutOfBoundsException: 7
        at ExcTest.genException(KH_Throwable.java:10)
        at KH_Throwable.main(KH_Throwable.java:18)
After catch statement.

Java’s Built-in Exception classes

Under java.lang package Java defines many exception classes to capture exceptions. Below is a list of exception classes available.

Exception Meaning
ArithmeticException Arithmetic error, such as integer divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible type.
ClassCastException Invalid cast.
EnumConstantNotPresentException An attempt is made to use an undefined enumeration value.
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 an incorrect state.
IllegalThreadStateException Requested operation not compatible with current thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException The 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.
StringIndexOutOfBoundsException Attempt to index outside the bounds of a string.
TypeNotPresentException Type not found.
UnsupportedOperationException An unsupported operation was encountered.
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.
ReflectiveOperationException Superclass of reflection-related exceptions.

Creating Custom Exception Class

Java provides a rich set of exception classes to use, but Java’s ability to handling exceptions is not limited to these built-in classes. Java allows us to write our own exception classes and use them as built-in classes. To create an exception class, it should be a subclass of Exception class. Of course, we can create a subclass of Throwable but in practice, we use Exception class as the superclass for our custom class. Exception class is also derived from Throwable and it does not do anything. Once we derived our class from Exception class, we can override any method which is present in Throwable class and create custom output.

In the below example, we have created a custom exception class NotEvenException and it is derived from Exception class. In this custom class, we override the toString method to display our custom string as output. In the main method, we have used catch blocks to catch our custom exception along with built-in exception classes. When given integer is not an even number then the main method throws our custom exception.

/*
This is a simple Java program about Exception Handling.
Call this file KH_CustomException.java.
*/

class NotEvenException extends Exception {
	int n;
	NotEvenException(int i) {
		n = i;
	}	
	public String toString() {
		return "The number " + n + " is not even number.";
	}
}
class KH_CustomException {
	
	public static void main(String args[]) {
		int number[] = { 4, 8, 15, 32, 64, 127, 256, 512 };
		for(int i=0; i<number.length; i++) {
			try {
				if((number[i]%2) != 0)
					throw new NotEvenException(number[i]);
				else
					System.out.println("The number " + number[i] + " is even number.");					
			}
			catch (ArithmeticException exc) {
				System.out.println("Can't divide by Zero!");
			}
			catch (ArrayIndexOutOfBoundsException exc) {
				System.out.println("No matching element found.");
			}
			catch (NotEvenException exc) {
				System.out.println(exc);
			}
		}
	}
}

Download the code  Run the code

Output:

The number 4 is even number.
The number 8 is even number.
The number 15 is not even number.
The number 32 is even number.
The number 64 is even number.
The number 127 is not even number.
The number 256 is even number.
The number 512 is even number.
<<< Multiple catch blocks and nested try blocksJava throw, finally and throws keywords >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .