Exception Handling in Java

What is an exception?

 

 

An exception may arise for a variety of causes.

Following are some scenarios where an exception occurs.

 

What is Exception Handling?

 

Hierarchy of Java Exception classes:

Types of exceptions

Checked exceptions

 

IOException:

Example:


Output:

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

ClassNotFoundException:

 

 

Example:


Output:

java.lang.ClassNotFoundException: DumbSchool

Unchecked Exceptions

 

ArithmeticException:

 


Output:

/by zero

Change value of a , a value can not be zero

Complete

NullPointerException:

 

Example:


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