Types of Exceptions in Java with Examples17 May 2025 | 8 min read In Java, an exception is an event that occurs during the execution of a program and disrupts the normal flow of the program's instructions. Bugs or errors that we don't want and restrict our program's normal execution of code are referred to as exceptions. In this section, we will focus on the types of exceptions in Java and the differences between the two. Types of ExceptionsExceptions can be categorized in two ways:
![]() Built-in ExceptionExceptions that are already available in Java libraries are referred to as built-in exception. These exceptions are able to define the error situation so that we can understand the reason of getting this error. It can be categorized into two broad categories, i.e., checked exceptions and unchecked exception. Checked ExceptionChecked exceptions are called compile-time exceptions because these exceptions are checked at compile-time by the compiler. The compiler ensures whether the programmer handles the exception or not. The programmer should have to handle the exception; otherwise, the system has shown a compilation error. Example of Checked ExceptionExampleCompile and RunOutput: Main.java:5: error: unreported exception FileNotFoundException; must be caught or declared to be thrown file_data = new FileInputStream("C:/Users/Desktop/Hello.txt"); ^ Main.java:7: error: unreported exception IOException; must be caught or declared to be thrown while(( m = file_data.read() ) != -1) { ^ Main.java:10: error: unreported exception IOException; must be caught or declared to be thrown file_data.close(); ^ 3 errors In the above code, we are trying to read the Hello.txt file to display its data on the console. When we execute the above program, we get the following exception:
Handling the Checked ExceptionsThere are basically two ways through which we can handle these exceptions. Using the throws Keyword The exceptions occur in the main() method. We can get rid of these compilation errors by declaring the exception in the main() method using the throws keyword. We only declare the IOException, not the FileNotFoundException, because of the child-parent relationship. The IOException class is the parent class of the FileNotFoundException class, so IOException automatically handles this exception. We will declare the exception in the following way: When we compile and run the above code by handling the IOException using the throws keyword, we get the following output: Hello Java Using try-catch Block We can also handle this exception by using the try-catch block. However, the way we have used above is not correct. We have to give a meaningful message for each exception because it would be easy to understand the error. We will use the try-catch block in the following way: ExampleCompile and RunOutput: File Not Found! Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.io.FileInputStream.read()" because "<local1>" is null at Main.main(Main.java:12) We will see a proper error message, "File Not Found!" on the console because there is no Hello.txt file at that location. We get the following message on the console. Unchecked ExceptionsThe unchecked exceptions are just the opposite of the checked exceptions. The compiler will not check these exceptions at compile time. In simple words, if a program throws an unchecked exception, and even if we did not handle or declare it, the program would not give a compilation error. Usually, it occurs when the user provides bad data during the interaction with the program. Note: The RuntimeException class is able to resolve all the unchecked exceptions because of the child-parent relationship.Example of Unchecked ExceptionsArithmeticException: Divide by Zero ExampleCompile and RunOutput: Runtime Error: Exception in thread "main" java.lang.ArithmeticException: / by zero at Main.main(Main.java:7) In the above program, we have divided 35 by 0. The code would be compiled successfully, but it will throw an ArithmeticException error at runtime. Dividing a number by 0 throws the divide by zero exception, which is an unchecked exception. Let's see another example of an unchecked exception. Example of ArrayIndexOutOfBoundsExceptionExampleCompile and RunOutput: Runtime Error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 6 at Main.main(Main.java:6) In the above code, we are trying to get the element located at position 7, but the length of the array is 6. The code compiles successfully, but throws the ArrayIndexOutOfBoundsException at runtime. User-defined ExceptionIn Java, we already have some built-in exception classes like ArrayIndexOutOfBoundsException, NullPointerException, and ArithmeticException. These exceptions are restricted to trigger on some predefined conditions. In Java, we can write our exception class by extending the Exception class. We can throw our exception on a particular condition using the throw keyword. For creating a user-defined exception, we should have basic knowledge of the try-catch block and throw keyword. Let's write a Java program and create user-defined exceptions. ExampleCompile and RunOutput: Exception value = 5 Explanation In the above code, we have created two classes, i.e., Main and NewException. The Main class has main() method, and the NewException class is a user-defined exception class that extends the Exception class. In the NewException class, we have created a variable x of type integer and assigned a value to it in the constructor. After assigning a value to that variable, we return the exception message. In the Main class, we have added a try-catch block. In the try block, we throw the exception, i.e., NewException and pass an integer to it. The value will be passed to the NewException class and return a message. We catch that message in the catch block and show it on the console. Differences Between Checked and Unchecked Exceptions
Bugs or errors that we do not want and restrict the normal execution of the programs are referred to as exceptions. ConclusionArithmeticException, ArrayIndexOutOfBoundsExceptions, ClassNotFoundExceptions, etc., fall in the category of Built-in Exceptions. Sometimes, the built-in exceptions are not sufficient to explain or describe certain situations. To describe these situations, we have to create our own exceptions by making an exception class as a subclass of the Exception class. These types of exceptions fall into the category of User-Defined Exception. 1. Which of the following is a checked exception in Java?
Answer: 3) Explanation: The compiler uses the try-catch or throws clause to require you to handle checked exceptions. The others are unchecked exceptions (subclasses of RuntimeException), whereas IOException is a checked exception. 2. What will be the output of the following code?
Answer: 3) Explanation: This is an example of an unchecked exception. An ArithmeticException is raised when dividing by zero during runtime. It compiles successfully but fails to execute since it is unchecked. 3. Which statement is true regarding checked exceptions in Java?
Answer: 4) Explanation: Checked exceptions must be stated using the throws keyword or handled manually with a try-catch block. 4. What will be the output of the following code?
Answer: 3) Explanation: A checked exception called FileNotFoundException is thrown by FileReader and needs to be handled or declared. It's not stated or caught, thus the compiler raises an error. 5. Identify the type of exception. What kind of exception is thrown, and how should the code be handled?
Answer: 2) Explanation: An unchecked exception called a NullPointerException is thrown at runtime by this code. Although try-catch can be used to handle it optionally, the compiler is not required to do so. |
In Java, static reference variables play a significant role in the overall structure and behaviour of a program. These variables hold references to objects or data that are shared across multiple instances of a class. By understanding static reference variables and their usage, developers can effectively...
4 min read
In this section, we will learn what is a sublime number and also create Java programs to check if the given number is a sublime number or not. The sublime number program is frequently asked in Java coding interviews and academics. Sublime Number A natural number N is...
2 min read
? The concept of inheritance allows classes to adopt features and attributes from other classes. It is a is fundamental OOPs concept. Because in single inheritance, a class can only descend from one superclass. However, Java offers a way to achieve multiple inheritances through interfaces. Using interface,...
5 min read
The java.text.ChoiceFormat is a class containing a hashcode() as a function. The hash code for the choice format object is obtained using the ChoiceFormat class. An integer representing this hashcode value is returned. Syntax: public int hashCode() Parameter: There are no parameters accepted by this method. Return Value: The...
2 min read
In Java, swapping or exchanging objects can be done by assigning one object's value to another object and vice versa. It can be done by using a temporary variable to hold the value of one object while it is being swapped with the value of another...
5 min read
Java usually uses GUI elements like JLabel or System.out.println() to capture and track printed output in order to determine the string sequence that appeared on the screen. It can be accomplished by dynamically storing the sequence of printed strings by rerouting System.out to a ByteArrayOutputStream or...
5 min read
It is a problem frequently asked in interviews of top IT companies like Google, Amazon, TCS, Accenture, etc. By solving the problem, one wants to check the logical ability, critical thinking, and problem-solving skill of the interviewee. So, in this section, we are going to solve...
6 min read
The digital signature is a mechanism that verifies the authority of digital messages as well as documents. It is very popular because it provides more security than other signatures. In Java, JDK Security API is used to create and implement digital signatures. In this section, we...
12 min read
Java provides two types of data types primitive and reference data type. The primitive data types are predefined in Java that serves as a fundamental building block while the reference data type refers to where data is stored. In this section, we will discuss what is a...
3 min read
In Java, deadlock is a part of multithreading. The multithreading environment allows us to run multiple threads simultaneously for multitasking. Sometimes the threads find themselves in the waiting state, forever that is a deadlock situation. The deadlock is a situation when two or more threads try to...
5 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India