Checked Exception Vs Unchecked Exception In Java

Checked Exception Vs Unchecked Exception In Java
Checked Exception Vs Unchecked Exception In Java

Introduction

Computers, unlike humans, are built to be perfect and cannot overlook errors. For example, let’s say the correct syntax for printing Hello is print(“Hello”), but the programmer omits one of the parentheses by accident. The computer will raise a syntax error and terminate the program.

Dealing with such coding errors is an integral part of every programmer’s life.

Regardless of one’s level of knowledge or experience, anyone who writes and manipulates computer code may encounter coding errors from time to time. 


This article will discuss checked exception vs unchecked exception in Java, followed by a brief overview of exception handling and the difference between exception and error.

“Exceptions are unwanted disruptions in the normal flow of the program’s instructions. They signify that something went wrong during the program’s execution.”

Want to learn more about exceptions, hierarchy, and their type? Check out our ultimate guide on Exceptions in Java: Hierarchy, Types and its Relation with Errors.

Before moving directly to the checked exception vs unchecked exception, let us first look at the primary reasons that cause exceptions in Java.

Causes of Exception in Java

Exceptions can result from severe hardware errors such as a hard disk crash or simple programming errors.  The Java Virtual Machine(JVM) detects an abnormal condition in the program and throws an exception in Java.

The abnormal condition in the program is majorly divided into three categories.

1. Violation of semantics of the language

Every programming language has rules for syntax and semantics, which defines valid ways of writing a program.  If a Java program violates the semantic constraints imposed by the language, the JVM throws an exception.

JVM  is short for Java Virtual Machine, which is an abstract machine. It is a specification that provides a runtime environment for executing Java bytecode.

Do you know about the Java Runtime Environment? If not, don’t worry, read this article on  Everything you need to know about the Java Runtime Environment.

Example: Dividing an integer or a decimal number by zero throws an exception.

import java.io.*;

public class Test {
    public static void main(String[] args)
    {
        int a = 17;
        int b = 0;
        System.out.print(a / b);
        // This line throws a divide by zero exception....
    }
}


Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at Test.main(Test.java:7)

2. Error in loading or linking part of the program

Before executing a program, JVM starts by loading and linking the required initialisation steps involved in executing the program.

  • The process of locating the binary form of a class or interface type with a specific name computed by the compiler is known as loading.
  • The process of combining a binary form of a class or interface type into the runtime state of the JVM so that it can be executed is known as linking.

If an error occurs while loading or linking a program, it’ll lead to an exception.

Example: A system-specific(native) function CFunction is defined in the program, which already exists in the java clibrary. This method is being called without the library being declared, resulting in a linkage error.

 public class TestError 
 {
	// Define a method that is defined externally.
    native void CFunction();

    // Loading an external library, called "clibrary".
    static {
         System.loadLibrary("clibrary");
    }

    public static void main(String argv[]) {
    	TestError e = new TestError();
         e.CFunction ();
    }
}


Output

Exception in thread "main" java.lang.UnsatisfiedLinkError: no clibrary in java.library.path: [C:\Program Files\Java\jdk-11.0.10\bin,
at java.base/java.lang.ClassLoader.loadLibrary(ClassLoader.java:2660)
	at java.base/java.lang.Runtime.loadLibrary0(Runtime.java:827)
	at java.base/java.lang.System.loadLibrary(System.java:1871)
	at TestError.<clinit>(TestError.java:8)

3. Limitation on a resource is exceeded.

The JVM is responsible for freeing up resources that are not being used by any program, such as memory space for objects that are no longer in use. When the JVM encounters a problem with resource utilisation, it will throw this type of exception.

Example: Insufficient space to allocate an object in the heap area throws an exception.

Types of Exception: Checked exception vs unchecked exception

In Java, there are two types of exceptions: checked exceptions and unchecked exceptions. Let’s take a closer look at them.

Checked Exceptions

  • A checked exception is the one that the compiler checks or notifies during compilation. 
  • Checked Exceptions are also known as compile-time exceptions
  • These exceptions cannot be ignored.
  • If a code within a function throws a checked exception, the function must handle the exception or specify it using the throws keyword.

For Example: 

A FileReader class is used in a file handling programme to read data from a file. If the file specified in its constructor does not exist, a FileNotFoundException occurs, and the compiler prompts the programmer to handle the exception.

Here, If the Name.txt file is not present in the specified location during the compilation, this code will throw an error.

import java.io.File;
import java.io.FileReader;

public class Test{

   public static void main(String args[]) {		
      File file = new File("E://Name.txt");
      FileReader fr = new FileReader(file); 
   }
}


Output: 

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Unhandled exception type FileNotFoundException

	at Test.main(Test.java:8)

Unchecked Exceptions

  • An unchecked exception occurs during the execution process. 
  • Unchecked Exceptions are also known as runtime exceptions
  • Programming mistakes, such as logic errors or improper use of an API, are examples of this. 
  • Runtime exceptions are ignored during compilation.
For Example: If a 7-element array is declared and the programme attempts to access its 8th element, an ArrayIndexOutOfBoundsExceptionexception occurs.

Here, the below program will be successfully compiled, but it’ll throw an exception at runtime.

public class Test{

	public static void main(String args[]) {
	      int num[] = {100, 20, 30, 40, 50, 60, 70};
	      System.out.println(num[7]);
	   }
	}


Output:

Exception in thread "main" java. Lang.ArrayIndexOutOfBoundsException: Index 8 out of bounds for length 7
	at Test.main(Test.java:7)

Differences: Checked exception vs Unchecked exception

The table below shows some of the notable differences between Checked and Unchecked exceptions in Java.

Key FactorsChecked ExceptionsUnchecked Exceptions
OccurrenceChecked exceptions occur at compile time.Unchecked exceptions occur at runtime.
Role of CompilerThe compiler checks a checked exception at compile time.The compiler does not check these exceptions.
HandlingHandled at compile time.Handled at run time.
Parent ClassException class is the direct parent class of the checked exception subclass.RuntimeException is the direct parent class of the Unchecked exception subclass.
Reason of OccurrenceA checked Exception occurs when the chances of failure are too high.Unchecked exceptions occur primarily due to syntax or semantic mistakes.
ExampleSQLException, IOException, ClassNotFoundException, InvocationTargetExceptionNullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, IllegalArgumentException,NumberFormatException

You might think of exceptions and errors as words that are analogous to each other. But they are not!

How are exceptions different from errors?

Java provides a rich library of built-in classes, and Throwable is one of them. Both Errors and Exceptions are subclasses of the Throwable class, the parent class of the hierarchy. Errors and Exceptions are two different branches of this hierarchy.

  • Errors are an abnormal condition that exception handling techniques cannot handle.
  • Errors are unchecked exceptions that occur at runtime and cause unusual termination of the program. 
  • The error indicates a problem that is typically caused by a lack of system resources, and our application is not designed to detect such issues. 
  • System failures and out-of-memory errors are two examples of errors.

For Example: In Java, a StackOverflowError is a runtime error. When the amount of call stack memory allocated by the JVM is exceeded, this error is thrown.

Exception Handling in Java

Having read all about exceptions, you must be wondering how to handle them. No doubt, Exceptions require special attention. If not handled correctly, at runtime, outcomes can be unfavorable. 

For example, an unhandled overflow exception was the reason for the historic Ariane 5 rocket launch mishap in 1996. Doubting how the number glitch can lead to catastrophe? Read here!

Exception handling is a promising feature in various programming languages. It allows us to handle runtime errors caused by exceptions.  

Java provides various keywords such as try, catch, finally, throw, and throws to handle exceptions. Each of these keywords has a specific function to perform. For example, a try block is used to enclose any code that might throw an exception. Similarly, the throws keyword is used to declare an exception in the program. 

Let’s move on to some frequently asked questions on checked exception vs unchecked exception.

Frequently Asked Questions

When would you use an unchecked exception?

If the exception is unpredictable, unpreventable, and unreasonable to recover, one should use an unchecked exception.

Should I use checked or unchecked exceptions?

Checked Exceptions should be used for predictable but unavoidable errors that are recoverable. For everything else, unchecked Exceptions should be used.

Is the ClassNotFoundException checked exception?

Yes, ClassNotFoundException is a checked exception.

Can we use throws for an unchecked exception?

Yes, throws can be used for unchecked exceptions, Although throws are usually used to handle checked exceptions.

Should we throw a runtime exception?

Yes, one should throw a runtime exception when an error occurs. In general, there are two types of situations in which you may need to throw a runtime exception:

Invalid parameter values: The majority of parameter validation exceptions should be handled at runtime. Java provides several subclasses for indicating these specific issues.

Methods called in the wrong order: Some methods cannot be called until a class has completed initialisation or elementary steps. Calls made in this intervening period result in runtime exceptions.

Why is Filenotfoundexception a checked exception?

An exception can be categorised as checked or unchecked based on its handling time. In Java, a FileNotFoundException is a checked exception. When we try to read a file from the filesystem, Java forces us to handle an error situation in which the file may not be present.

Key Takeaways:

In the checked exception vs unchecked exception, we learned that checked exceptions occur at compile time when the chances of failure are too high. In contrast, unchecked exceptions arise at runtime primarily due to syntax mistakes.

Eventually, after knowing the causes, types, and key differences between checked exception vs unchecked exception, you should start looking for ways to handle these exceptions in Java.

Don’t know where to start looking for ways to handle exceptions, check out our next blog on Exception Handling in Java using try-catch and finally.

Java is a powerful general-purpose, object-oriented programming language used to develop mobile applications, web applications, big data processing, embedded applications and is supported by billions of devices worldwide.

Aspire to become the next face of Java Developer? Don’t miss checking out our Java Foundation course with Data Structures & Algorithms

and Java Cheat Sheet equipped with the knowledge of Data Structures and Algorithms plus the proper understanding of the rich API and powerful development tools of programming.

If you need more hands-on experience in Java, you can practice problems on CodeStudio. Here, you will get more than 2115 DSA problems frequently asked in interview rounds, along with the interview experiences of scholars in big product-based companies.

By Vaishnavi Pandey

Exit mobile version