• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Types of Exceptions in Java – Checked, Unchecked, & Error

July 7, 2020 by javainterviewpoint Leave a Comment

In this article, we will learn about the different types of exceptions in Java checked exceptions, unchecked exceptions, and errors.

Exceptions can happen in any scenario, and all developers would have come across exceptions, for example, whenever we try to read a file that doesn’t exist or whenever we try to read the elements in an array beyond its size and so on.

It is always better to know which exception occurs in which situation so that we will have better control in handling the exception.

Types of Exceptions in Java

Exceptions can be divided into three main categories

  1. Checked exceptions (Compile-time exceptions)
  2. Unchecked exceptions (Runtime exceptions)
  3. Errors

Types of Exceptions in Java
All the exceptions descend from the Throwable class, and then the hierarchy splits into two branches Error and Exception.

Error hierarchy describes the internal error or any resource exhaustion or any other malfunction which happens in the JVM. On the other hand, the Exceptions branch further splits into two IOException and Runtime exceptions.

Except for the Error and RuntimeException and its subclasses, all other classes will be a part of Checked Exception (Compile-time exception).

Checked Exception happens on the occurrence of events which is beyond the control of the JVM like File not present or reading from the database where there might be a situation that the database is down etc.

Whereas Runtime Exception happens due to bad programming such as not handling null properly, dividing a number by zero, etc.

Let’s discuss them in detail

1. Checked Exception or Compile Time Exception:

A Checked Exception or Compile-Time Exception is a subclass of the java.lang.Exception but not a subclass of java.lang.RuntimeException.

Checked Exception is the exception that will be checked during the compile-time, if a method throws a checked exception then the calling method must have one of the below

  • A try-catch block to handle the exception

(or)

  • Throw the exception using throws keyword in the method signature

A checked exception occurs whenever we are doing some operation that is not in the control of the JVM.

For example, Let’s try to open a file.

package com.javainterviewpoint;

import java.io.FileInputStream;

public class FileRead
{
   public static void main(String[] args)
   {
      FileInputStream fileInputStream = new FileInputStream("test.txt");
   }
}

The above code throws a compile-time exception “FileNotFoundException”, as there can be a possibility of file not present at the mentioned location.

When we look at the constructor of FileInputStream,

public FileInputStream(String name) throws FileNotFoundException {
        this(name != null ? new File(name) : null);
    }

The declaration says that the above constructor produces the FileInputStream object using the string parameter passed, and in case of any issues, it will throw FileNotFoundException.

Types of Exceptions in Java - Checked Exception

In order to make the above code work we need to enclose it in the try-catch block or throw the exception

package com.javainterviewpoint;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class FileRead
{
   public static void main(String[] args)
   {
      try
      {
         FileInputStream fileInputStream = new FileInputStream("test.txt");
      } catch (FileNotFoundException e)
      {
         e.printStackTrace();
      }
   }
}

2. Unchecked Exception or RunTimeException:

A Runtime Exception or Uncheck Exception is a subclass of java.lang.RunTimeException class. Runtime exception usually occurs because of bad programming or programming error.

Since the Unchecked exceptions happen during the run time, we don’t need to throw the exception in the method signature, though we can do it but not mandatory.

For example, NullPointerExecption is a type of RunTimeException which occurs when a variable is not assigned an object and still points to null.

package com.javainterviewpoint;

public class NullTest
{
   public static void main(String[] args)
   {
      String name = null;
      System.out.println(name.length());
   }
}

The above code clearly shows that the exception occurred due to bad programming. A simple null check before performing any operation on the variable will sort out the issue.

package com.javainterviewpoint;

public class NullTest
{
   public static void main(String[] args)
   {
      String name = null;
      if (name != null)
         System.out.println(name.length());
   }
}

Like the Checked exception, we can use a try-catch to catch the runtime exception.

package com.javainterviewpoint;

public class NullTest
{
   public static void main(String[] args)
   {
      String name = null;
      try
      {
         System.out.println(name.length());
      } catch (NullPointerException ne)
      {
         System.out.println("NullPointerException has occured!!");
      }
   }
}

3. Error

An Error is a subclass of java.lang.Error class. The Error indicates a severe issue that cannot be controlled through the code.

For example, OutOfMemoryError occurs when the Java Heap space is full, StackOverflowError is another error which the JVM throws when the stack required for the program is higher than the memory allocated by the JRE.

package com.javainterviewpoint;

public class StackOverFlow
{
   public static void main(String args[])
   {
      disp();
   }

   public static void disp()
   {
      disp();
   }
}

The above code eventually throws StackOverFlowError as the disp() method runs infinite number of times.

Exception in thread "main" java.lang.StackOverflowError
	at com.javainterviewpoint.StackOverFlow.disp(StackOverFlow.java:12)
	at com.javainterviewpoint.StackOverFlow.disp(StackOverFlow.java:12)
	at com.javainterviewpoint.StackOverFlow.disp(StackOverFlow.java:12)
	at com.javainterviewpoint.StackOverFlow.disp(StackOverFlow.java:12)
	at com.javainterviewpoint.StackOverFlow.disp(StackOverFlow.java:12)
	at com.javainterviewpoint.StackOverFlow.disp(StackOverFlow.java:12)
	at com.javainterviewpoint.StackOverFlow.disp(StackOverFlow.java:12)

Tough Error represents a severe issue, and we should not handle it, we can still catch the Error like below.

package com.javainterviewpoint;

public class StackOverFlow
{
   public static void main(String args[])
   {
      try
      {
         disp();
      } catch (StackOverflowError se)
      {
         System.out.println("StackOverflowError has occured!!");
      }
   }
   public static void disp()
   {
      disp();
   }
}

Happy Learning!!

Filed Under: Core Java, Java Tagged With: Checked Exception, Compile-Time Exception, Error, Exception, RuntimeException, Types of Exceptions in Java, Unchecked Exception

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·