What Are Checked And Unchecked Exceptions In Java

The Checked And Unchecked Exceptions In Java, a checked exception is a condition in your code that can be fixed or tried again, while an unchecked exception is a programming error that can’t be fixed.

In this tutorial, we will talk about Exceptions In Java. This is a continuation of the previous topic, entitled Java.io and Files.

An Exception In Java is an unwanted or unexpected event that happens while a program is running and stops the instructions from being carried out in the usual way.

What Are Checked Exceptions In Java?

In Java, a checked exception, also called a logical exception, is something that has gone wrong in your code but might be fixable.

At the time of compilation, these exceptions are checked. If some code inside a method throws a checked exception, the method must either handle the exception or specify it using the throws keyword.

The following listed below are 2 types of exceptions in Java.

  • Fully check exceptions
  • Partially check exceptions

For example, the following Java program opens the file at “C:\test\a.txt” and prints the first three lines of it. The program doesn’t compile because the function main() calls FileReader(), and FileReader() throws a checked exception called FileNotFoundException. It also uses the readLine() and close() methods, which both throw checked exceptions. IOException

Example

// program created by Glenn
// Java Program to Illustrate Checked Exceptions
// Where FileNotFoundException occurred

// Importing I/O classes
import java.io.*;

// Main class
public class PIES {

	// Main driver method
	public static void main(String[] args)
	{

		// Reading file from path in local directory
		FileReader file = new FileReader("C:\\test\\a.txt");

		// Creating object as one of ways of taking input
		BufferedReader fileInput = new BufferedReader(file);

		// Printing first 3 lines of file "C:\test\a.txt"
		for (int counter = 0; counter < 3; counter++)
			System.out.println(fileInput.readLine());

		// Closing file connections
		// using close() method
		fileInput.close();
	}
}

Output

/PIES.java:16: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
FileReader file = new FileReader(“C:\test\a.txt”);
^
/PIES.java:23: error: unreported exception IOException; must be caught or declared to be thrown
System.out.println(fileInput.readLine());
^
/PIES.java:27: error: unreported exception IOException; must be caught or declared to be thrown
fileInput.close();
^
3 errors

In order for you to test your Java code provided in this lesson, you must test the code in your code editor. But if you wish to run this code online, we also have an online compiler in Java for you to test your java code for free.

We also provide a Java Online Compiler for every code below. Just scroll down so that you can easily test or execute the source code.

To fix the above program, we need to either list the exceptions using throws or use a try-catch block. The program below uses throws. Since FileNotFoundException is a subclass of IOException, we can just put IOException in the throws list and make the above program compile without any errors.

Example

// program crreated by Glenn
// Java Program to Illustrate Checked Exceptions
// Where FileNotFoundException does not occur

// Importing I/O classes
import java.io.*;

// Main class
public class PIES {

	// Main driver method
	public static void main(String[] args)
		throws IOException
	{

		// Creating a file and reading from local repository
		FileReader file = new FileReader("C:\\test\\a.txt");

		// Reading content inside a file
		BufferedReader fileInput = new BufferedReader(file);

		// Printing first 3 lines of file "C:\test\a.txt"
		for (int counter = 0; counter < 3; counter++)
			System.out.println(fileInput.readLine());

		// Closing all file connections
		// using close() method
		// Good practice to avoid any memory leakage
		fileInput.close();
	}
}

Output

The First three lines of file “C:\test\a.txt”

What Are Unchecked Exceptions In Java?

An Unchecked Exception In Java, also called a runtime exception, is something that has gone wrong with a Java program and can’t be fixed.

These are the exceptions that aren’t checked at compile time. All exceptions are unchecked in C++, so the compiler doesn’t force you to either handle or specify the exception.

Look at the next Java program. It compiles fine, but when it’s run, it throws an ArithmeticException. ArithmeticException is an unchecked exception, so the compiler lets it compile.

Example

// program created by Glenn
// Java Program to Illustrate Un-checked Exceptions

// Main class
public class PIES {

	// Main driver method
	public static void main(String args[])
	{
		// Here we are dividing by 0
		// which will not be caught at compile time
		// as there is no mistake but caught at runtime
		// because it is mathematically incorrect
		int g = 1;
		int x = 20;
		int z = g / x;
	}
}

Output

Exception in thread “main” java.lang.ArithmeticException: / by zero
at Main.main(Main.java:5)
Java Result: 2

What Is The Difference Between Unchecked And Checked Exceptions?

The Difference Between Unchecked And Checked Exceptions a Checked Exceptions are checked when the program is running, but Unchecked Exceptions are checked when the program is being compiled.

What Are The Different Types Of Exceptions In Java

The following listed below are the two main types of exceptions in Java.

  • Checked exception
  • Unchecked exception
Exceptions in Java
Exceptions in Java

How To Handle Multiple Exceptions In Java?

The only way to Handle Multiple Exceptions In Java is must use the Java multi-catch block.

One or more catch blocks can come after a try block. Each catch block must have its own handler for an error. So, if you need to do different things when different exceptions happen, you can use the Java multi-catch block.

Java Exceptions Try Catch

The try statement lets you set up a block of code that will be checked for errors as it runs.

With the catch statement, you can set up a block of code to run if an error happens in the try block.

Syntax Of Java Exceptions Try Catch

try {
// Basic syntax
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}

Parent Class Of All Exceptions In Java

The Parent Class Of All Exceptions In Java is the java.lang.Exception.

The class Exception and its subclasses are type of Throwable that shows situations that an application might want to catch.

The following figure shows the different kinds of Java exceptions.

different kinds of Java exceptions
different kinds of Java exceptions

Errors vs Exceptions In Java

Errors are usually caused by the environment where the application is running. For instance, an error will happen when there aren’t enough system resources. Exceptions are created by the code of the application itself. Errors can’t be fixed.

How To Throw Multiple Exceptions In Java

In Java, we might have to deal with several exceptions. You can’t throw multiple exceptions in Java. We can list multiple exceptions, but only one will be thrown.

But there are a few other ways we can simulate throwing more than one exception.

When we need to handle more than one exception, we can use “chained exceptions.” These kinds of exceptions mean that the one that was thrown was caused by another exception.

Example

// program created by Glenn
public class Main
{
    public static void main(String[] args)
    {
        try
        {
            NumberFormatException ex =
                    new NumberFormatException("NumberFormatException is thrown");
            ex.initCause(new NullPointerException(
                    "NullPointerException is the main cause"));
            throw ex;
        }

        catch(NumberFormatException ex)
        {
            System.out.println(ex);
            System.out.println(ex.getCause());
        }
    }
}

Output

java.lang.NumberFormatException: NumberFormatException is thrown
java.lang.NullPointerException: NullPointerException is the main cause

When Does Exceptions In Java Arises In Code Sequence

Exceptions in Java arises in code sequence in Run Time.

Because Exceptions are determined at run time in Java, they are errors that happen at run time.

What Are Runtime Exceptions In Java With Example?

A Runtime Exceptions In Java are things that happen inside your application and usually can’t be fixed.

For example, a null object is one that should have a value but doesn’t. A NullPointerException exception would be thrown in this case.

The following are the 10 most common examples of runtime exceptions in Java:

  • ArithmeticException
  • NullPointerException
  • ClassCastException
  • DateTimeException
  • ArrayIndexOutOfBoundsException
  • NegativeArraySizeException
  • ArrayStoreException
  • UnsupportedOperationException
  • NoSuchElementException
  • ConcurrentModificationException

Summary

In summary, you have learned about What Are Checked And Unchecked Exceptions In Java. This tutorial has covered the following topics: What Are Checked Exceptions In Java, What Are Unchecked Exceptions In Java, Difference Between Unchecked And Checked Exceptions, Different Types Of Exceptions In Java, Try and Catch, Parent Class Of All Exceptions and Runtime Exceptions. I use NetBeans IDE to test all the source code given in the lesson.

I hope this lesson has helped you learn What Are Checked And Unchecked Exceptions In Java.

What’s Next

The next section talks about Inner Class In Java. At the end of the session, you’ll know what Inner Class all about in Java.


Leave a Comment