Exception Handling in Java

What is an exception?

An Exception is an unwanted event that interrupts the normal flow of the program. When an exception occurs program execution gets terminated. In such cases, we get a system-generated error message. An exception can occur for many different reasons. Following are some scenarios where an exception occurs.

  • A user has entered invalid data.
  • A file that needs to be opened cannot be found.
  • A network connection has been lost in the middle of communications or the JVM has run out of memory.

What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Hierarchy of Java Exception classes:

Types of exceptions

There are two types of exceptions in Java:

  • Checked exceptions
  • Unchecked exceptions

Checked exceptions

All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks them during compilation to see whether the programmer has handled them or not. If these exceptions are not handled/declared in the program, you will get a compilation error. For example, SQLException, IOException, ClassNotFoundException, etc.

IOException:

The IOException is an exception thrown when an I/O error occurs. It is also the base class of such exceptions which occur while reading or accessing files, directories, and streams. The IOException belongs to the class of checked exceptions. Checked exceptions are those exceptions that are thrown at compile-time. It is necessary to resolve checked exceptions to execute a Java program. There are many subclasses of IOException like FileNotFoundException, EndOfStreamExceptionDirectoryNotFoundException, etc.
Example:

public class fileReader{
   public static void main (String[] args){

      try {
          FileReader reader = new FileReader("C:\\Java\\readFile.txt");
          BufferedReader bufferedReader = new BufferedReader(reader);
          String line;
          while ((line = bufferedReader.readLine()) != null) {
             System.out.println(line);
          }
      } 
      catch (FileNotFoundException exception) {
	       System.out.println(exception.getMessage());
	
      }
      catch (IOException exception) {
	       System.out.println(exception.getMessage());
      }
  }//main
}//class

Output:

C:\Java\rreadFile.txt (The system cannot find the file specified)

ClassNotFoundException:

In Java ClassNotFoundException occurs when JVM (Java Virtual Machine) tries to load a particular class and doesn’t found the requested class in the classpath you specified. This means that your classpath is broken (which is a very common problem in the Java world ). This problem can be particularly confusing for Java beginners. ClassNotFoundException is a checked exception, so it has to be catch or thrown to the caller.

Example:

public class fileReader{
   public static void main (String[] args){

      // Try block to check for exceptions
       try {

           Class.forName("DumbSchool");
       }

       // Catch block to handle exceptions
       catch (ClassNotFoundException ex) {

           // Displaying exceptions on console along with
           // line number using printStackTrace() method
           ex.printStackTrace();
       }
   }//main
}//class

Output:

java.lang.ClassNotFoundException: DumbSchool

Unchecked Exceptions

Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked at compile-time so the compiler does not check whether the programmer has handled them or not but it’s the responsibility of the programmer to handle these exceptions and provide a safe exit. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc.

ArithmeticException:

An arithmetic exception in Java is a Runtime exception present in Java. lang package. JVM throws Arithmetic Exception when a wrong mathematical expression occurs in a Java program. The base class of Java arithmetic exception is Java. langArithmetic exception which comes under Java. lang.RuntimeException.

Example:

 public class fileReader{
   public static void main (String[] args){

     int a=10; 
     int b=0; 
     int c=0; 
     try {
       c=a/b; //risk statement 
     } 
     catch(ArithmeticException e) { 
       System.out.println(e.getMessage());
       System.out.println("Change value of a ,a value can not be zero");
     } 
     finally { 
       System.out.println("Complete"); 
     }
 }//main
}//class

Output:

/by zero

Change value of a , a value can not be zero

Complete

NullPointerException:

The null pointer exception in Java is a runtime exception, which is thrown when the program tries to use an object reference that is set to the null value. Refer to the following coding example to understand the null pointer exception in Java.

Example:

public class fileReader{
  public static void main (String[] args){

     String s=null; 
     try {
        System.out.println(s.length()); 
     }
     catch (NullPointerException e) { 
        System.out.println(e.getMessage()); 
        System.out.println("The value of s is null");
     }
  }//main
}//class

Output:

/by zero

Change value of a, a value can not be zero

ArrayIndexOutOfBoundsException:

In Java, ArrayIndexOutOfBoundsException is an exception that occurs when we try to access an array element at an index that is outside the bounds of the array. This means that the index being accessed is either negative or greater than or equal to the size of the array.

Example:

public class fileReader{
   public static void main (String[] args){
     int []number= {1,5,7,9};		
    try {
       System.out.println(number[4]);
    }
    catch(ArrayIndexOutOfBoundsException e){
       System.out.println(e.getMessage());
       System.out.println("Array index out of bound");
    }
  }//main
}//class

Output:

Index 4 out of bounds for length 4

Array index out of bound

StringIndexOutOfBoundsException:

In Java, a StringIndexOutOfBoundsException is a runtime exception when you try to access a character in a String at an invalid index. Attempting to access a character at an index that is either negative or outside the range of the String’s length causes this exception to be thrown.

Example:

public class fileReader{
   public static void main (String[] args){


      //Index number starts from 0 in String and Array.
                        0123
      String letters = "ABCD";              
      try {
          System.out.println( letters.charAt(4) );
       }
      catch (StringIndexOutOfBoundsException m) {
          System.out.println(m.getMessage());
          System.out.println("you string index number is out of bound");
      }
   }//main
}//class

Output:

String index out of range: 4

 

 

 





Visited 1 times, 1 visit(s) today

Comments are closed.

Close