digitization, transformation, binary

Common Exception Classes in Java With Example

Spread the love

This post talks about Exception Classes in Java,predefined exception classes in java,creating exception classes in java,different exception classes in java,exception handling classes in java,common exception classes in java,built in exception classes in java,checked exception classes in java,what are exception classes in java,all exception classes in java.

Table of Contents

Exception Classes in Java

ArrayIndexOutOfBound Exception in Java:

Before we look for this class, we need to understand the Array. Click here to understand more about an Array.
Arrays are blocks of memory and if a program tries to access the Array that is outside of the memory block(Array), or tries to use the memory block before initializing, there will be unpredictable results.
So all arrays may contain either primitive or nonprimitives (Objects). Any Array element falls between 0 to its length-1. Checking the access of array for each element can be a source of inefficiency of code.

This exception is thrown by java compiler to indicate that the coder may have accessed outside of its bounds or illegal index has been passed to access the Array.
The illegal index could be negative, greater than or equal to the size of the array.

The structure of the class ArrayIndexOutOfBoundsException looks like the below:

public class java.lang.ArrayIndexOutOfBoundsException extends java.lang.IndexOutOfBoundsException{
//Contructors
public ArrayIndexOutOfBoundsException();// This constructor contructs an ArrayIndexOutOfBoundsException with no message
public ArrayIndexOutOfBoundsException(String message);//This constructor constructs and ArrayIndexOutOfBoundsException with the message specified
public ArrayIndexOutOfBoundsException(int index); //This constructor constructs an ArrayIndexOutOfBoundsException with the illegal index that is out of bound.
}
 

The class ArrayIndexOutOfBound also inherits methods from Object and Throwable class:

From Object classFrom Throwable class
clone()fillInStackTrace()
getClass()getMessage()
notify()printStackTrace()
wait()printStackTrace(PrintWriter)
wait(long, int)getLocalizedMessage()
wait(long)printStackTrace(PrintStream)
equals(Object)
toString()
finalize()
hashCode()
notifyAll()

Here is an example to show how this exception occurs in java coding:

public class ArrayTest{
public static void main(String[] args)    
{
int a[]={1,2,3};
for(int i=0;i<=a.length;i++)
{
System.out.println(a[i]);
}
}
}

the output of the code:
$javac ArrayTest.java
$java -Xmx128M -Xms16M ArrayTest
1
2
3
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 3
at ArrayTest.main(ArrayTest.java:7)

Notice here: the compiler did compile the code but it failed at runtime. This is an unchecked exception so the compiler does not check for the correctness. During Runtime the exception has been caught. The exception has been thrown as we tried to access an element that is 4(greater than the capacity limit of the array) and outside of the bound. Check the for the loop – it starts with 0 and should go till a.lenth-1

IllegalMonitorStateException in Java:

IllegalMonitorStateException is thrown when a thread has tried to wait on an object’s monitor or to notify other threads waiting on an object’s monitor, without owning the specified monitor.
A  monitor is a piece of code to use for synchronizing threads by indicating the current state of the thread that owns it. This exception IllegalMonitorStateException is thrown if that state becomes illegal. It is thrown by the Object’s notify(),notifyAll() and wait() methods that are used for thread synchronization.

The structure of the class IllegalMonitorStateException as follows:

public class java.lang.IllegalMonitorStateExceptionextends java.lang.RuntimeException{
//constructor
public IllegalMonitorStateException();
//constructs an empty IllegalMonitorStateException object that is an object with no message specified.
public IllegalMonitorStateException(String message);
//constructs an IllegalMonitorStateException object with the message specified.
}

The class IllegalMonitorStateException also inherits methods from class Object and Throwable.

From Object classFrom Throwable class
clone()fillInStackTrace()
getClass()getMessage()
notify()printStackTrace()
wait()printStackTrace(PrintWriter)
wait(long, int)getLocalizedMessage()
wait(long)printStackTrace(PrintStream)
equals(Object)
toString()
finalize()
hashCode()
notifyAll()

IllegalArgumentException Class in Java:

IllegalArgumentException is thrown to indicate that a method has passed an illegal or inappropriate argument while calling another method. It is a general-purpose exception that can be thrown by a library that receives an illegal argument. We may choose to throw it by the method that is accessed with wrong or illegal arguments. It can also occur if one attempts to pass a parameter that is invalid range or value for a method.

READ  Constant Concept Simplified in Java

The structure of IllegalArgumentException class is as below:

public class java.lang.IllegalArgumentException extends java.lang.RuntimeException{
//constructor
public IllegalArgumentException();
//constructs an empty IllegalArgumentException object that is an
// object with no message specified.
public IllegalArgumentException(String message);
//constructs an IllegalArgumentException object with the message specified.
}

The class IllegalArgumentException also inherits methods from class Object and Throwable.

From Object classFrom Throwable class
clone()fillInStackTrace()
getClass()getMessage()
notify()printStackTrace()
wait()printStackTrace(PrintWriter)
wait(long, int)getLocalizedMessage()
wait(long)printStackTrace(PrintStream)
equals(Object)
toString()
finalize()
hashCode()
notifyAll()
Example of IllegalArgumentException in java:
static double division(int myArg)
{
if (myArg==0)
throw new IllegalArgumentException("argument can not be zero for division");
else
return x/myArg;
}
 

OptionalDataException class in java

OptionalDataException is thrown by the readObject() method of an ObjectInputStream when it encounters primitive type data where it expects object data. Despite the exception name, this data is not ” optional, and object deserialization is aborted.
It may cause either the eof flag is true, or the length variable indicates the number of bytes that are available to be read.

The class structure of OptionalDataException class in given as


public class java.io.OptionalDataException extends java.io.ObjectStreamException
// No Constructor
// Public Instance Variables
public boolean eof;
public int length;
}

The details of the OptionalDataException is given as:

public boolean eof;

A boolean value that indicates if the stream is at its end.

public int length;

The number of available bytes of data.
The class OptionalDataException also inherits methods from class Object and Throwable.

From Object classFrom Throwable class
clone()fillInStackTrace()
getClass()getMessage()
notify()printStackTrace()
wait()printStackTrace(PrintWriter)
wait(long, int)getLocalizedMessage()
wait(long)printStackTrace(PrintStream)
equals(Object)
toString()
finalize()
hashCode()
notifyAll()

IllegalAccessException class in java

IllegalAccessException is thrown when an application tries instantiate a class and try to  load a class through its String name using any of the following methods:

  1. forName(), this method is defined in Class Class.
  2. findSystemClass(),this method is defined in class ClassLoader.
  3. loadClass(),this method is defined in class ClassLoader.

but the currently executing method does not have access to the definition of the specified class, because the class is not public or maybe in another package or may not have a public constructor.

So basically we tried to call a method that has restricted access. An instance of this class can also be thrown when an application tries to create an instance of a class using the newInstance() method in class Class but the current method does not have access to the appropriate zero-argument constructor. Chain method calling may also suffer from this exception.

In short, Signals that a class or initializer is not accessible. Thrown by Class.newInstance().
This exception is also thrown when a program tries to create an instance
of a class (i.e., uses the newInstance() method of the Class class) that does not have a zero-argument
constructor accessible to the caller.

The structure of the IllegalAccessException class is defined as below:

public class java.lang.IllegalAccessException extends java.lang.Exception{
//constructor
public IllegalAccessException();
//constructs an empty IllegalAccessException object that is an object with no message specified.
public IllegalAccessException(String message);
//constructs an IllegalAccessException object with the message specified.
}

The class IllegalAccessException also inherits methods from class Object and Throwable.

From Object classFrom Throwable class
clone()fillInStackTrace()
getClass()getMessage()
notify()printStackTrace()
wait()printStackTrace(PrintWriter)
wait(long, int)getLocalizedMessage()
wait(long)printStackTrace(PrintStream)
equals(Object)
toString()
finalize()
hashCode()
notifyAll()

CloneNotSupportedException in Java:

CloneNotSupportedException is thrown from the code to indicate that the clone() method in the class Object has been called to clone an object but the Object’s class does not implement the Cloneable interface.

Applications that override the clone() method can also throw this exception to indicate that the object could not be or should not be cloned.

The structure of the class CloneNotSupportedException as follows:

public class java.lang.CloneNotSupportedException extends java.lang.Exception{
//constructor
public CloneNotSupportedException();
//constructs an empty CloneNotSupportedException object that is an object with no message specified.
public CloneNotSupportedException(String message);
//constructs an CloneNotSupportedException object with the message specified.
}

The class CloneNotSupportedException also inherits methods from class Object and Throwable.

From Object classFrom Throwable class
clone()fillInStackTrace()
getClass()getMessage()
notify()printStackTrace()
wait()printStackTrace(PrintWriter)
wait(long, int)getLocalizedMessage()
wait(long)printStackTrace(PrintStream)
equals(Object)
toString()
finalize()
hashCode()
notifyAll()

IntrospectionException in Java

Signals that introspection on a Java bean could not be completed. Typically this indicates a bug in the way the bean or its associated BeanInfo class is defined.

public class java.beans.IntrospectionException extends java.lang.Exception {
pub// Public Constructor 915
public IntrospectionException (String mess);
}

ObjectStreamException in Java

ObjectStreamException class is the superclass of a number of more specific exception types that may be raised in the process of serializing and deserializing objects with the objectOutputStream and ObjectInputStream classes.

public abstract class Object java.io.ObjectStreamException extends java.io.IOException{
// Protected Constructors
protected ObjectStreamException (String classname);
protected ObjectStreamException ();
}

The details of the methods are given as:

protected ObjectStreamException (String classname);

protected ObjectStreamException (String classname) constructor creates an ObjectStreamException with the specified detail message, which should be the name of the class that caused the exception.

READ  Class StreamCorruptedException in java

Parameter
classname-The name of the class.

protected ObjectStreamException ();

protected ObjectStreamException () constructor creates an ObjectStreamException with no detail message.
The class ObjectStreamException also inherits methods from class Object and Throwable.

From Object classFrom Throwable class
clone()fillInStackTrace()
getClass()getMessage()
notify()printStackTrace()
wait()printStackTrace(PrintWriter)
wait(long, int)getLocalizedMessage()
wait(long)printStackTrace(PrintStream)
equals(Object)
toString()
finalize()
hashCode()
notifyAll()

ClassNotFoundException in Java

ClassNotFoundException is thrown from a program when an application tries to load in a class through its String name using any of the below methods:

  1. forName(), this method is defined in Class Class.
  2. findSystemClass(),this method is defined in class ClassLoader.
  3. loadClass(),this method is defined in class ClassLoader.

but no definition for the class with the specified name is found. In short, this exception signals that a class to be loaded is not found.

The structure of the ClassNotFoundException class is given below:

public class java.lang.ClassNotFoundException extends java.lang.Exception{
//constructor
public ClassNotFoundException ();
//constructs an empty ClassNotFoundException object that is an object with no message specified.
public ClassNotFoundException(String message);
//constructs an ClassNotFoundException object with the message specified.
}

The class ClassNotFoundException also inherits methods from class Object and Throwable.

From Object classFrom Throwable class
clone()fillInStackTrace()
getClass()getMessage()
notify()printStackTrace()
wait()printStackTrace(PrintWriter)
wait(long, int)getLocalizedMessage()
wait(long)printStackTrace(PrintStream)
equals(Object)
toString()
finalize()
hashCode()
notifyAll()

Class ClassCastException in Java

Casting refers to the terminology where an instance of a class of one type can be made to cast for another type. But there is a rule to it. An instance of a class can be cast to its superclass but one can not cast an instance of a class to its subclasses.

ClassCastException is thrown from a program to indicate that the code has attempted to cast an object to a subclass of which it is not an instance or it could be due to incorrect type.

in short, it signals an invalid cast of an object to a type of which it is not an instance.
However, it is possible to avoid this exception by checking the type first using instanceOf operator or method.

The structure of the class ClassCastException is as follows:


public class java.lang.ClassCastException extends java.lang.RuntimeException{
//constructor
public ClassCastException();
//constructs an empty ClassCastException object that is an object with no message specified.
public ClassCastException(String message);
//constructs an ClassCastException object with the message specified.
}
 

Let us check some examples: In this example assume that Class ClassA has two child classes ClassB and ClassC.
ClassA
/           \
ClassB ClassC

class ClassA{
}
class ClassB extends ClassA{
void MethodB()
{
....
}
}
class ClassC extends ClassA{
void MethodC()
{
....
}
}
class Test{
void castTest()
{
//possible
ClassA a new ClassA();
ClassB b=(ClassB)new ClassA();
ClassA b=new ClassB();
ClassA a1=new ClassC();
//not possible
ClassB b1=new ClassC();
ClassB b2=new new ClassA();
ClassC c1=new ClassB();
}
} 

The class ClassCastException also inherits methods from class Object and Throwable.

From Object classFrom Throwable class
clone()fillInStackTrace()
getClass()getMessage()
notify()printStackTrace()
wait()printStackTrace(PrintWriter)
wait(long, int)getLocalizedMessage()
wait(long)printStackTrace(PrintStream)
equals(Object)
toString()
finalize()
hashCode()
notifyAll()

ArrayStoreException in Java:

ArrayStoreException is thrown out of a program to indicate that an attempt to store the wrong type of object into an array of different types of objects.(Incompatible type store)

The structure of the class ArrayStoreException as follows:

public class java.lang.ArrayStoreException extends java.lang.RuntimeException{
//constructor
public ArrayStoreException ();
//constructs an empty ArrayStoreException object that is an object with no message specified.
public ArrayStoreException (String message);
//constructs an ArrayStoreException object with the message specified.
}
Apart from these, ArrayStoreException also inherits methods from Class Object and  Throwable. They are as follows:
From Object classFrom Throwable class
clone()fillInStackTrace()
getClass()getMessage()
notify()printStackTrace()
wait()printStackTrace(PrintWriter)
wait(long, int)getLocalizedMessage()
wait(long)printStackTrace(PrintStream)
equals(Object)
toString()
finalize()
hashCode()
notifyAll()
Example of ArrayStoreException:

This exception occurs when one tries to store a value in an array of an incompatible class or type.


void wrongArrayStore()
{
int storeArray=new int[15];
boolean booArray=new boolean[5];
System.arrayCopy(storeArray,2,booArray,2,4);
}
 

The output of the code will be an ArrayStoreException.

Class NoSuchElementException in Java

NoSuchElementException is thrown by mostly the nextElement() method of an enumeration to indicate that there are no more elements in the Enumeration (such as vector) or the stack is empty.

The structure of the NoSuchElementException class is given by

public class java.util.NoSuchElementException extends
             java.lang.RuntimeException{
//constructors
public NoSuchElementException();
//default constructor and constructs a NoSuchElementException with no details message.
public NoSuchElementException(String message);
//constructs a NoSuchElementException with the message passed in the argument
}

StringOutOfBoundsException in Java:

StringOutOfBoundsException is thrown from an application’s chatAt(index i) method in class String or by another String method when tried to access a character that is outside the boundary or the bounds of a String. or a StringBuffer. This is mainly to indicate that an index is either negative, equal to the size of the String or greater than the size of the String.

The structure of the class StringOutOfBoundsException is given by:

public class java.lang.StringOutOfBoundsException extends java.lang.IndexOutOfBoundsException{
//constructor
public StringOutOfBoundsException();
//constructs an empty StringOutOfBoundsException object that is an object with no message specified.
public StringOutOfBoundsException(String message);
//constructs an StringOutOfBoundsException object with the message specified.
public StringOutOfBoundsException(int index);
//constructs an StringOutOfBoundsException object with the argument indicating the illegal index.
} 
Example of StringOutOfBoundsException

-An attempt to access a nonexistent character position in a String.

public void myStringMethod()
{
String myString="Love";
char myChar=myString.charAt(7);
} 

The class stringoutofboundse also inherits methods from class Object and Throwable.

From Object classFrom Throwable class
clone()fillInStackTrace()
getClass()getMessage()
notify()printStackTrace()
wait()printStackTrace(PrintWriter)
wait(long, int)getLocalizedMessage()
wait(long)printStackTrace(PrintStream)
equals(Object)
toString()
finalize()
hashCode()
notifyAll()
READ  Abstract Class HttpURLConnection in Java

Class UTFDataFormatException in Java

UTFDataFormatException class signals that a malformed UFT-8 String has been read in a data input stream or by any class that implements the DataInput interface.

A UTFDataFormatException is thrown when there is an attempt to read a UTF string from a stream that does not contain a properly formatted UTF string.
An IOException that signals that a malformed UTF-8 string has been encountered by a class that implements the DataInput interface. UTF-8 is an ASCII-compatible “transformation format” for Unicode characters that are often used to store and transmit Unicode text.

The structure of the class UTFDataFormatException is given as:

public class java.io.UTFDataFormatException extends java.io.IOException{
//constructors
public UTFDataFormatException ();
//constructs an empty UFTDataFormatException object that is an object with no message specified.
public UTFDataFormatException (String message);
//constructs an UFTDataFormatException object with the message specified with parameter s.
}

The class-UTFDataFormatException also inherits methods from Object and Throwable class. They are as follows:

From ObjectFrom Throwable
clone()fillInStackTrace()
getClass()getMessage()
notify()printStackTrace()
wait()printStackTrace(PrintWriter)
wait(long, int)getLocalizedMessage()
wait(long)printStackTrace(PrintStream)
equals(Object)
toString()
finalize()
hashCode()
notifyAll()

IllegalStateException in Java

IllegalStateException is common exception classes in java and is thrown from code to indicate that a method has been invoked on an object that is not in an appropriate state to be able to perform the specified operation.

The structure of the class IllegalStateException in Java is given as:

public class java.lang.IllegalStateException extends java.lang.RuntimeException{
//constructor
public IllegalStateException();
//constructs an empty IllegalStateException object that is an object with no message specified.
public IllegalStateException(String message);
//constructs an IllegalStateException object with the message specified.
} 

The class IllegalStateException also inherits methods from class Object and Throwable.

From Object classFrom Throwable class
clone()fillInStackTrace()
getClass()getMessage()
notify()printStackTrace()
wait()printStackTrace(PrintWriter)
wait(long, int)getLocalizedMessage()
wait(long)printStackTrace(PrintStream)
equals(Object)
toString()
finalize()
hashCode()
notifyAll()

Class BindException In Java:

An application can throw this -BindException exception to indicate a socket could not be bound to the local address and port. It is a very common exception class in java.

The structure of BindException is given as:

public class java.net.BindException extends java.io.SocketException{
//constrcutors:
public BindException();//default constrcutor
public BindException(String message);
} 

Class EOFException in Java

EOFException is popular built-in exception classes in java and is thrown from an application indicating that an end of file has been reached unexpectedly during input. This exception is mainly used by DataInputStream classes. This class expects a binary file in a specified format and for which the end of the stream is an unusual condition. Most other input Streams return a special value on the end of Streams.

The structure of the class EOFException is given as:


public class java.io.EOFException extends java.io.IOException{
//constructor
public EOFException();
//constructs an empty EOFException object that is an object with no message specified.
public EOFException(String message);
//constructs an EOFException object with the message specified.
}

WriteAbortedException in java:

An application throws WriteAbortedException in java when it tries reading a Stream of data that is incomplete as an exception was thrown while it was being written. The deleted field holds the exception that terminated the output stream.

A WriteAbortedException is thrown during object deserialization when the stream of data is incomplete because an exception was thrown while it was being written. Thus, WriteAbortedException represents an exception that was thrown during object serialization and serialized into the stream.

The overridden getMessage() method provides the detailed exception message.

The structure of WriteAbortedException in java is given as:


public class java.io.WriteAbortedException extends
             java.io.ObjectStreamException{
//member element:
public Exception details; //The exception that was thrown during serialization; it is a subclass of ObjectStreamException.
//constructor
public WriteAbortedException(String msg,Exception e);
//methods
public String getMessage();
}
 
public WriteAbortedException(String msg,Exception e);

This constructor creates a WriteAbortedException with the specified reason string. The created exception wraps the given exception thrown during serialization.
Parameters-
msg – A description of the reason this exception was thrown.
e -The exception that was thrown during serialization.

public String getMessage();

This method returns the detail message of this exception, as well the detail message of the nested exception if it exists. This is an overridden version of the Throwable.getMessage() method.
The class-WriteAbortedException also inherits methods from Object and Throwable class. They are as follows:

From ObjectFrom Throwable
clone()fillInStackTrace()
getClass()getMessage()
notify()printStackTrace()
wait()printStackTrace(PrintWriter)
wait(long, int)getLocalizedMessage()
wait(long)printStackTrace(PrintStream)
equals(Object)
toString()
finalize()
hashCode()
notifyAll()

Here is the list of different exception classes in java, built-in exception classes in java.

Class ArithmeticException in Java:

ArithmeticException is thrown to indicate that an exceptional arithmetic condition has occurred. Example divide by zero.

The class structure is as follows:

public class java.lang.ArithmeticException extends java.lang.RuntimeException{
//constructor
public ArithmeticException();
//constructs an empty ArithmeticException object that is an object with no message specified.
public ArithmeticException(String message);
//constructs an ArithmeticException object with the message specified as in argument.
}

The Class-ArithmeticException also inherits methods from Object and Throwable:

From Object classFrom Throwable class
clone()fillInStackTrace()
getClass()getMessage()
notify()printStackTrace()
wait()printStackTrace(PrintWriter)
wait(long, int)getLocalizedMessage()
wait(long)printStackTrace(PrintStream)
equals(Object)
toString()
finalize()
hashCode()
notifyAll()

Ref- Oracle Exception classes


Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *