Java

Java – Exception Handling Examples

In this lesson, we’ll look at several instances of common exceptions and learn how to correctly manage them using try-catch blocks. We’ll examine how to handle the following exceptions: NullPointerException, StringIndexOutOfBoundsException, NumberFormatException, and ArithmeticException.

I strongly advise you to read to this beginner’s guide: Exception handling in Java if you are unfamiliar with the idea of exception handling.

Example 1: Arithmetic exception

When the outcome of a division operation is unclear, this exception occurs. This exception happens when the result of dividing an integer by zero is undefinable.

class JavaExample
{
  public static void main(String args[])
  {
    try{
      int num1=30, num2=0;
      int output=num1/num2;
      System.out.println ("Result: "+output);
    }
    catch(ArithmeticException e){
      System.out.println ("You Shouldn't divide a number by zero");
    }
  }
}

Output of above program:

You Shouldn't divide a number by zero

Example 2: ArrayIndexOutOfBounds Exception

When you attempt to access an array index that doesn’t exist, this exception is thrown. For instance, if an array only has five items and you attempt to show the seventh member, an exception will be raised.

class JavaExample
{
  public static void main(String args[])
  {
    try{
      int a[]=new int[10];
      // This will throw exception as Array has
      // only 10 elements and we are trying to access
      // 12th element.
      a[11] = 9;
    }
    catch(ArrayIndexOutOfBoundsException e){
      System.out.println ("ArrayIndexOutOfBounds Exception occurred");
      System.out.println ("System Message: "+e);
    }
  }
}

Output:

 

In the aforementioned example, the array is initialized to hold only 10 entries, indexed from 0 to 9. This error is being thrown by the application because we are attempting to access an element with index 11.

Example 3: NumberFormat Exception

The array in the aforementioned example has just 10 elements, indexed from 0 to 9. We are trying to access an element with index 11, hence the program is throwing this problem.

class JavaExample
{
  public static void main(String args[])
  {
    try{
      int num=Integer.parseInt ("XYZ") ;
      System.out.println(num);
    }catch(NumberFormatException e){
      System.out.println("Number format exception occurred");
    }
  }
}

Output:

Number format exception occurred

Example 4: StringIndexOutOfBound Exception

Class: Java.lang.StringIndexOutOfBoundsException

  • An array of the string type is all that a string is. Similar to the ArrayIndexOutOfBoundsException, this error happens when you attempt to access an index that doesn’t exist.
  • Each character in a string object is kept in its own index, which starts at 0. For instance, the character “b” is saved in the string “beginnersbook” at index 0, followed by the character “e” at index 1, and so on.
  • Using the java.lang.String function charAt(int), where int parameter is the index, we may get a character that is present at a certain index of a string.
class JavaExample
{
  public static void main(String args[])
  {
    try{
      String str="beginnersbook";
      System.out.println(str.length());
      char c = str.charAt(40);
      System.out.println(c);
    }catch(StringIndexOutOfBoundsException e){
      System.out.println("StringIndexOutOfBoundsException.");
    }
  }
}

Output:

13
StringIndexOutOfBoundsException.

Exception occurred because the referenced index was not present in the String.

Example 5: NullPointer Exception

Class: Java.lang.NullPointer Exception

When attempting to execute an operation on an object that has a reference to null, this exception will occur.

class JavaExample
{
  public static void main(String args[])
  {
    try{
      String str=null;
      System.out.println (str.length());
    }
    catch(NullPointerException e){
      System.out.println("NullPointerException..");
    }
  }
}

Output:

NullPointerException..

The method that should be used to an object in this case is length(). However, the String object str in the example above is null, thus it is not an object, which is why a NullPointerException happened.

Related Articles

Leave a Reply

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

Back to top button