Java’s Built-in Exceptions
- In java.lang package have several exception classes.
- The most general of these exceptions are RuntimeException and that sub classes that's why there is no need to throw these Exceptions implicitly which are called as unchecked exceptions because the compiler does not check to see if a method handles or throws these exceptions.
Exception | Meaning |
---|---|
Arithmetic Exception | Arithmetic error, such as divide-by-zero |
ArrayIndexOutOfBoundsException | Array index is out-of-bounds |
ArrayStroreException | 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 is used to invoke a method |
IllegalMonitorStateException | Illegal monitor operation, such as waiting on an unlocked thread. |
IllegalStateException | Environment or application is in incorrect state. |
IllegalThreasStateException | 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 null reference. |
NumberFormatException | Invalid conversion of a string to a numeric format. |
SecurityException | Attempt to violate security. |
StringIndexOutOfBounds | Attempt to index outside the bound of a string. |
TypeNotPresentException | Type not found. |
UnsupportedOperationException | An unsupported operation was occured. |
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 a interface. |
InterruptedException | One thread has been interrupted by another thread. |
NoSuchFieldException | A requested field does not exist. |
NoSuchMethodException | A requested method does not exist. |
ReflectionOperationException | Superclass of reflection- related exceptions. |
Creating Our Own Exception Sub classes
We can create our own Exceptions by simply creating the sub class to the Exception Class which is the subclass of Throwable.
We can override the one or more methods in Exception classes.
Exception defines four public constructors.
Exception( )- has no description
Exception(String msg)-provides description for Exception.
//example for creating sub class from Exception overriding toString() method
// 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 + "]";
}
}
public 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);
}
}
}
Output:
Called compute(1)
Normal exit
Called compute(20)
Caught MyException[20]
Chained Exceptions
- The chained exception feature allows us to associate another exception with an exception.
Example: an ArithmeticException is occurs due to divide by zero. However, the actual cause of the problem was that an I/O error occurred, which caused the divisor to be set improperly. Although the method must certainly throw an ArithmeticException, since that is the error that occurred, you might also want to let the calling code know that the underlying cause was an I/O error.
To allow chained exceptions, two constructors and two methods were added to Throwable.
The constructors are :
Throwable(Throwable causeExc)- causeExc is the underlining cause of the Exception
Throwable(String msg, Throwable causeExc)- msg provides the description of the Exception.
The methods are:
Throwable getCause( )-returns the exception that underlies the current exception. If there is no underlying exception, null is returned.
Throwable initCause(Throwable causeExc)-associates cause Exc with the invoking exception and returns a reference to the exception.
// Demonstrate exception chaining.
public class ChainExcDemo
{
static void demoproc()
{
// create an exception
NullPointerException e = new NullPointerException("top layer");
// add a cause
e.initCause(new ArithmeticException("cause"));
throw e;
}
public static void main(String args[])
{
try
{
demoproc();
}
catch(NullPointerException e)
{
// display top level exception
System.out.println("Caught: " + e);
// display cause exception
System.out.println("Original cause: " + e.getCause());
}
}
}
Output:
Caught: java.lang.NullPointerException: top layer
Original cause: java.lang.ArithmeticException: cause
Three Recently Added Feature in Exceptions
These are added in the beginning of JDK7.
Automating the process of releasing the resources.
- EX: Releasing files when there is no longer need for the file.
- This is done by the use of try statement called try-with-resources.
Multi-catch feature
- This allows us to caught two or more exceptions by using single catch block with parameters as two or more exceptions.
- The code for the exceptions is not same but it can handle those exceptions.
Each exception type in the catch clause should be separate by the OR operator.
Each multi-catch parameter is implicitly final.
Ex: catch(ArithmeticException | ArrayIndexOutOfBoundsException e)
// example for the multi-catch feature.
public class MultiCatch
{
public static void main(String args[])
{
int a=10, b=0;
int vals[] = { 1, 2, 3 };
try
{
int result = a / b; // generate an ArithmeticException
//vals[10] = 19; // generate an ArrayIndexOutOfBoundsException
// This catch clause catches both exceptions.
}
catch(ArithmeticException | ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception caught: " + e);
}
System.out.println("After multi-catch.");
}
}
Output:
Exception caught: java.lang.ArithmeticException: / by zero
After multi-catch.
final rethrow or more precise rethrow.
This feature restricts the type of exceptions that can be rethrown to only those checked exceptions that the associated try block throws, that are not handled by a preceding catch clause, and that are a subtype or supertype of the parameter