BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java Exception Handling Examples

Last Updated: October 25, 2022 by Chaitanya Singh | Filed Under: java

In this tutorial, we will see examples of some of the popular exceptions and how to handle them properly using try-catch block. We will see exception handling of ArithmeticException, ArrayIndexOutOfBoundsException, NumberFormatException, StringIndexOutOfBoundsException and NullPointerException.

If you are new to the concept of exception handling, I highly recommend you to refer this starter guide: Exception handling in Java.

Example 1: Arithmetic exception

This exception occurs when the result of a division operation is undefined. When a number is divided by zero, the result is undefined and that is when this exception occurs.

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

This exception occurs when you try to access an array index that doesn’t exist. For example, If array is having only 5 elements and you are trying to display 7th element then it would throw this exception.

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:

Exception output

In the above example the array is initialized to store only 10 elements indexes 0 to 9. Since we are trying to access element of index 11, the program is throwing this exception.

Example 3: NumberFormat Exception

This exception occurs when a string is parsed to any numeric variable.
For example, the statement int num=Integer.parseInt ("XYZ"); would throw NumberFormatException because String “XYZ” cannot be parsed to int.

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

  • A string is nothing but an array of string type. This exception occurs when you try to access an index that doesn’t exist, similar to what we have seen in ArrayIndexOutOfBoundsException.
  • Each character of a string object is stored in a particular index starting from 0. For example: In the string “beginnersbook”, the char ‘b’ is stored at index 0, char ‘e’ at index 1 and so on.
  • To get a character present in a particular index of a string we can use a method charAt(int) of java.lang.String where int argument is the index.

In the following example, the scope of the string “beginnersbook” is from index 0 to 12, however we are trying to access the char at index 40, which doesn’t exist, hence the exception occurred.

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
This exception occurs when you are trying to perform some operation on an object that references to the null value.

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

Here, length() is the function, which should be used on an object. However in the above example String object str is null so it is not an object due to which NullPointerException occurred.

Recommended Posts

  • User defined Exception in Java
  • How to catch multiple exceptions in Java
  • Checked and Unchecked exceptions in Java
  • throw vs throws in Java
❮ PreviousNext ❯

Top Related Articles:

  1. Exception handling in Java with examples
  2. Nested try catch block in Java – Exception handling
  3. Interface in java with example programs
  4. What is case Keyword in Java
  5. Constructor Overloading in Java with examples

Tags: Exception-Handling

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. Shraban says

    January 22, 2016 at 12:11 PM

    It would be better if you describe “Exception Handling with Method Overriding.”

    Reply
  2. N3al says

    April 3, 2017 at 1:12 AM

    good examples really enjoyed they are straight forward

    Reply
  3. muthukumar says

    August 2, 2017 at 1:57 AM

    very useful!!!

    Reply

Leave a Reply Cancel reply

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

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap