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

Exception handling in Java with examples

By Chaitanya Singh | Filed Under: java

Exception handling is one of the most important feature of java programming that allows us to handle the runtime errors caused by exceptions. In this guide, you will learn what is an exception, types of it, exception classes and how to handle exceptions in java with examples.

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.

The good thing about exceptions is that java developer can handle these exception in such a way so that the program doesn’t get terminated abruptly and the user get a meaningful error message.

For example: You are writing a program for division and both the numbers are entered by user. In the following example, user can enter any number, if user enters the second number (divisor) as 0 then the program will terminate and throw an exception because dividing a number by zero gives undefined result. To get the user input, we are using Scanner class. Notice the output of the program.

import java.util.Scanner;
public class JavaExample {

  public static void main(String[] args) {

    int num1, num2;
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter first number(dividend): ");
    num1 = scan.nextInt();

    System.out.print("Enter second number(divisor): ");
    num2 = scan.nextInt();

    int div = num1/num2;
    System.out.println("Quotient: "+div);
  }
}

Output:

Arithmetic exception when not handled

As you can see, the user input caused the program to throw Arithmetic exception, however this is not a good programming practice to leave such exceptions unhandled. Let’s handle this exception.

Exception Handling in Java

Here, we are trying to handle the exception that is raised in the above program. You can see that the program ran fine and gave a meaningful error message which can be understood by the user.

Note: Do not worry about the try and catch blocks as we have covered these topics in detail in separate tutorials. For now just remember that the code that can throw exception needs to be inside try block and the catch block follows the try block, where the exception error message is set.

import java.util.Scanner;
public class JavaExample {

  public static void main(String[] args) {

    int num1, num2;
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter first number(dividend): ");
    num1 = scan.nextInt();

    System.out.print("Enter second number(divisor): ");
    num2 = scan.nextInt();
    try {
      int div = num1 / num2;
      System.out.println("Quotient: "+div);
    }catch(ArithmeticException e){
      System.out.println("Do not enter divisor as zero.");
      System.out.println("Error Message: "+e);
    }

  }
}

Output:

Handling arithmetic exception in java

If an exception occurs, which has not been handled by programmer then program execution gets terminated and a system generated error message is shown to the user.

These system generated messages are not user friendly so a user will not be able to understand what went wrong. In order to let them know the reason in simple language, we handle exceptions. We handle such exceptions and then prints a user friendly warning message to user, which lets them correct the error as most of the time exception occurs due to bad data provided by user.

Why we handle the exceptions?

Exception handling ensures that the flow of the program doesn’t break when an exception occurs. For example, if a program has bunch of statements and an exception occurs mid way after executing certain statements then the statements, that occur after the statement that caused the exception will not execute and the program will terminate abruptly. By handling we make sure that all the statements execute and the flow of execution of program doesn’t break.

Why an exception occurs?

There can be several reasons that can cause a program to throw exception. For example: Opening a non-existing file in your program, Network connection problem, bad input data provided by user etc. Let’s see few scenarios:
1. ArithmeticException:
We have already seen this exception in our example above. This exception occurs when we divide a number by zero. If we divide any number by zero.

int num = 25/0;//ArithmeticException

2. NullPointerException:
When a variable contains null value and you are performing an operation on the variable. For example, if a string variable contains null and you are comparing with another string. Another example is when you are trying to print the length of the string that contains null.

String str = null;  

//NullPointerException
System.out.println(str.length());

3. NumberFormatException:
This exception occurs where there is a type mismatch. Let’s say you are trying to perform an arithmetic operator on a string variable.

String str = "beginnersbook.com"; 

//NumberFormatException  
int num=Integer.parseInt(str);

4. ArrayIndexOutOfBoundsException:
When you are trying to access the array index which is beyond the size of array. Here, we are trying to access the index 8 (9th element) but the size of the array is only 3. This exception occurs when you are accessing index which doesn’t exist.

int arr[]=new int[3]; 

//ArrayIndexOutOfBoundsException  
arr[8]=100;
Exception classes hierarchy

Difference between error and exception

Errors indicate that something went wrong which is not in the scope of a programmer to handle. You cannot handle an error. Also, the error doesn’t occur due to bad data entered by user rather it indicates a system failure, disk crash or resource unavailability.

Exceptions are events that occurs during runtime due to bad data entered by user or an error in programming logic. A programmer can handle such conditions and take necessary corrective actions. Few examples:
NullPointerException – When you try to use a reference that points to null.
ArithmeticException – When bad data is provided by user, for example, when you try to divide a number by zero this exception occurs because dividing a number by zero is undefined.
ArrayIndexOutOfBoundsException – When you try to access the elements of an array out of its bounds, for example array size is 5 (which means it has five elements) and you are trying to access the 10th element.

Types of exceptions

Types of Exceptions in Java

There are two types of exceptions in Java:
1) Checked exceptions
2) Unchecked exceptions

I have covered these topics in detail in a separate tutorial: Checked and Unchecked exceptions in Java.

1) 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 compilation error. For example, SQLException, IOException, ClassNotFoundException etc.

2) Unchecked Exceptions

Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked at compile-time so 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. The examples that we seen above were unchecked exceptions.
Note: Compiler doesn’t enforce you to catch such exceptions or ask you to declare it in the method using throws keyword.

Frequently used terms in Exception handling

try: The code that can cause the exception, is placed inside try block. The try block detects whether the exception occurs or not, if exception occurs, it transfer the flow of program to the corresponding catch block or finally block. A try block is always followed by either a catch block or finally block.

catch: The catch block is where we write the logic to handle the exception, if it occurs. A catch block only executes if an exception is caught by the try block. A catch block is always accompanied by a try block.

finally: This block always executes whether an exception is occurred or not.

throw: It is used to explicitly throw an exception. It can be used to throw a checked or unchecked exception.

throws: It is used in method signature. It indicates that this method might throw one of the declared exceptions. While calling such methods, we need to handle the exceptions using try-catch block.

What topics are covered in the next tutorials

You can read these topics to understand the exception handling concept in detail. You can also practice various programs covered in the following tutorials.

  1. Try-catch in Java
  2. Nested Try Catch
  3. Checked and unchecked exceptions
  4. Finally block in Java
  5. try-catch-finally
  6. finally block & return statement
  7. Throw exception in Java
  8. Example of throw keyword
  9. Example of throws clause
  10. Throws in Java
  11. throw vs throws
  12. Exception handling examples
❮ PreviousNext ❯

Comments

  1. sravani says

    July 11, 2014 at 6:33 AM

    hi Chaitanya Singh,

    thanks for your efforts it is really appreciated.this is the best site i have ever seen. very clear explanation. please upload the frameworks also.then it will be very helpful to us.

    Reply
  2. Poornima says

    July 18, 2014 at 9:01 AM

    Explanation is good… Thanks

    Reply
    • akash says

      August 27, 2015 at 8:23 AM

      good reply

      Reply
  3. satyabrata barik says

    August 26, 2014 at 12:26 PM

    Hi Chaitanya,

    Thanks a lot for putting such hard work for us and I can say this is the most simplest website where the beginners really will be start focusing. It helped me and I usually go through your others subject when i get some time.

    Reply
  4. sampath says

    September 10, 2014 at 3:17 AM

    Am Lecturer in Computer Science, This site is an Excellent site. Very Good Explanation and easy understandable examples. very good. update frequently.

    Reply
  5. kumar vishal says

    October 29, 2014 at 3:53 AM

    Explanation is good.But, try to give more examples. Examples are so easy. For programming examples should be more for practices.

    Reply
  6. Harsh says

    March 12, 2015 at 6:02 PM

    Please tell me how to handle checked and unchecked exception with example?

    Reply
    • Ashfaq says

      November 16, 2015 at 12:15 PM

      Same mechanism is used to handle any exception. Difference between checked and unchecked exception is that if you don’t handle checked exception using try…catch block in your program then it will not compile.

      Reply
  7. Vikram says

    May 20, 2015 at 11:30 AM

    Hi,
    THis is very good site having explanation of core concepts in very simple manner.

    Regards
    Vikram

    Reply
  8. chandrasekhar says

    October 26, 2015 at 7:36 PM

    Hi Chaitanya,
    beginnersbook helped me a lot.Thank you.

    Reply
  9. Abhinav Kumar says

    December 3, 2015 at 6:50 PM

    Hi Chaitanya,

    Beginners Book is really one of the best to the ground sites for the basic JAVA learners.
    Thanks a lot for it…!!

    Reply
  10. hajra says

    January 25, 2016 at 12:59 PM

    thank you so much for a simple and clear explanation…

    Reply
  11. Nawal Sah says

    February 17, 2016 at 6:55 AM

    What is the difference between compiler error and exception?

    Reply
    • praveen says

      March 2, 2017 at 10:02 AM

      Compiler error:when we compile the program then we will get compile time error.

      Exception:an unwanted unexpected event disturbs the normal flow of the program execution.

      Reply
  12. Nawal Sah says

    February 17, 2016 at 6:57 AM

    What code block should we never return from and why?

    Reply
  13. Nawal Sah says

    February 17, 2016 at 7:02 AM

    What is Error? Can we catch Errors? If yes, what should be done in the catch block and why?

    Reply
  14. Chitra says

    September 9, 2016 at 7:49 AM

    thanks a lot.. it is nice blog to know the java concepts.. simple and easy yar… :)

    Reply
  15. Brian Wekesa says

    December 19, 2016 at 9:14 AM

    good work I enjoyed reading it……….#bryan

    Reply
  16. Sandor Szekeres says

    December 27, 2016 at 1:47 PM

    “When an exception occurs program processing gets terminated and doesn’t continue further.”

    It is not strictly true… If we handle the exception correctly then it can continue processing.
    Am I right?

    See the first exception of this article:
    https://beginnersbook.com/2013/04/try-catch-in-java/

    Reply
  17. Deepan says

    June 20, 2017 at 1:06 PM

    The way you have explained is really awesome, also you have provided the examples where ever required.

    thanks for your great effort.

    Reply
  18. Gajanan Kharat says

    September 1, 2017 at 6:33 AM

    Hello Chaitanya,

    Nice explanation about Exception handling but Could you please elaborate How ClassNotFoundException
    comes under the “Checked Exception”, I guess it should be unchecked exception

    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 – 2022 BeginnersBook . Privacy Policy . Sitemap