Exception Classes in Java With Example

0
586
Spread the love
  • 67
  • 99
  • 55
  • 45
  •  
  •  
  •  
  • 18
  •  
  •  
    284
    Shares

Exception Classes in Java
Exception Classes in Java
Exception Classes in Java

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.

Exception Classes in Java

ArrayIndexOutOfBound Exception in Java:

Before we really look for this class, we need to understand the Array. Click here to understand more about an Array–here.
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 class looks like the below:

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

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 which 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

IllegalThreadStateException in Java:

IllegalThreadStateException is thrown from code to indicate that the thread is not in an appropriate state for the required or requested operation.The call to sleep() method is enclosed with a try block followed by a catch block. The sleep() method may throw an exception,which needs to be caught and handle.
Java throws IllegalThreadStateException whenever we attempt to invoke a method that a thread can not handle in the given state.

Example-

A sleeping thread can not deal with the resume() method as a sleeping thread can not receive any messages or instructions.It is even true with the suspend() method when it is used on a blocked(Not runnable) thread.

or The thread may be already started and running when we want to start the same thread.

The structure of the class is as follows:

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

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 notify() and wait() methods which are used for thread synchronization.

The structure of this class 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.
}

IllegalArgumentException Class in Java:

IllegalArgumentException is thrown to indicate that a method has passed an illegal or inappropriate arguments 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 is accessed with wrong or illegal arguments.It can also occur if one attempts to pass a parameter that is not in valid range or value for a method.

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

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

IllegalAccessException class in java

IllegalAccessException is thrown when an application tries instantiate a class and tries to  load a class through its String name using the 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 may be 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.

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

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

ClassNotFoundException in Java

ClassNotFoundException is thrown from a program when an application tries to load in a class through it’s 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.

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

Class ClassCastException in Java

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

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 67
  • 99
  • 55
  • 45
  •  
  •  
  •  
  • 18
  •  
  •  
    284
    Shares

LEAVE A REPLY

Please enter your comment!
Please enter your name here