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. |
A prerequisite for an independent set of graphs is the set of vertices in which no two are neighboring. Just by definition, it is the opposite of a clique, so understanding a graph's complements is essential to moving on. In essence, the concept of a planar...
17 min read
Finding the factor (divisor) that appears the most frequently among all of the array's elements is known as the Maximum Factor Score. We see the divisors of each integer in the array and tally how often they occur. The factor with the highest count determines the...
5 min read
Java is a popular and powerful programming language known for its platform independence and robustness. Over the years, Java has evolved, introducing various features and APIs to enhance its capabilities. One such evolution is Project Panama, which aims to improve the connection between Java and native...
4 min read
What is TDD? Test-driven development, or TDD for short, is a software development process. As the name implies, involves utilizing tests to guide application development, resulting in simple, iterative implementation with good test coverage right from the start. Test-Driven Designing and building tests for each single function of...
3 min read
In the world of Java programming, data structures play a critical position in dealing with and organizing records correctly. One such facts structure that proves to be extremely beneficial is the EnumMap. EnumMaps are specialized Map implementations in Java designed to work with Enum keys. In...
8 min read
A basic polyalphabetic substitution technique is used in the Vigenere Cypher to encrypt alphabetic text. It is more secure than a conventional Caesar cipher since it employs a keyword to move letters in the plaintext by varying amounts. In this section, we will explain the Vigenere...
5 min read
What is Authentication? Authentication is the process of verifying the credentials a user provides with those stored in a system to prove the user is who they say they are. If the credentials match, then we grant access. If not, we deny it. Methods of Authentication Single Factor authentication: This...
6 min read
How to convert byte array to String in Java? The process of converting a byte array to a String is called decoding. This process requires a Charset. Though, we should use charset for decoding a byte array. There are two ways to convert byte array to String: By using...
7 min read
In the world of Java programming, developers often encounter the terms "container" and "component." These terms are fundamental to Java's graphical user interface (GUI) development, and understanding their distinctions is crucial for creating robust and modular applications. In this section, we will explore the key differences...
4 min read
In this section, we will learn how to multiply two numbers without using the arithmetic operator (*) in Java. The multiplication of two numbers can be found by the repeated addition method. It means that add the number (multiplicand) into itself up to multiplicator times. The method...
3 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