Exception Handling in Java

What is an exception?

An undesirable occurrence that halts the program’s regular flow is called an exception. Program execution is stopped when an exception happens.

In such cases, we get a system-generated error message.

An exception may arise for a variety of causes.

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?

An approach to deal with runtime problems like ClassNotFoundException, IOException, SQLException, RemoteException, etc. is called exception handling.

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 indicates that your classpath is broken, which is a rather typical issue with Java. Beginners to Java may find this particular issue very confusing.

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. It is the responsibility of the programmer to handle these exceptions and offer a safe exit because they are not examined by the compiler during compile time. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc.

ArithmeticException:

An arithmetic exception in Java is a Runtime exception present in Java. lang package.

When an incorrect mathematical expression appears in a Java program, JVM throws an Arithmetic Exception. Java is the base class of the Java arithmetic exception.

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:

When an object reference that is set to the null value is attempted to be used by the program, a runtime exception known as the null pointer exception in Java is raised. To learn about the Java null pointer exception, see the code example below.

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,

When we try to access an array element at an index that is outside the array’s bounds, we get the ArrayIndexOutOfBoundsException exception. This indicates that the index being read is either equal to, larger than, or negative than the array’s size.

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 runtime issue known as StringIndexOutOfBoundsException occurs when you attempt to access a character in a String at an incorrect index. This exception is thrown when a character is attempted to be accessed at an index that is either negative or outside the String’s length range.

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