Java Checked vs Unchecked Exceptions Last Updated : 03 Jun, 2025 Summarize Comments Improve Suggest changes Share Like Article Like Report In Java, an exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at run time, that disrupts the normal flow of the program’s instructions. In Java, there are two types of exceptions:Checked Exception: These exceptions are checked at compile time, forcing the programmer to handle them explicitly.Unchecked Exception: These exceptions are checked at runtime and do not require explicit handling at compile time.Difference Between Checked and Unchecked ExceptionsChecked ExceptionUnchecked ExceptionChecked exceptions are checked at compile time.Unchecked exceptions are checked at run time.Derived from Exception.Derived from RuntimeException.Caused by external factors like file I/O and database connection cause the checked Exception.Caused by programming bugs like logical errors cause unchecked Exceptions.Checked exceptions must be handled using a try-catch block or must be declared using the throws keywordNo handling is required.Examples: IOException, SQLException, FileNotFoundException.Examples: NullPointerException, ArrayIndexOutOfBoundsException.Checked Exceptions in JavaChecked Exceptions are exceptions that are checked at compile time. If a method throws a checked Exception, then the exception must be handled using a try-catch block and declared the exception in the method signature using the throw keyword.Types of Checked ExceptionFully Checked Exception: A checked exception where all its child classes are also checked (e.g., IOException, InterruptedException).Partially Checked Exception: A checked exception where some of its child classes are unchecked (e.g., Exception).Checked exceptions represent invalid conditions in areas outside the immediate control of the program like memory, network, file system, etc. Any checked exception is a subclass of Exception. Unlike unchecked exceptions, checked exceptions must be either caught by the caller or listed as part of the method signature using the throws keyword. Example: Java // Java Program to Illustrate Checked Exceptions // Where FileNotFoundException occurs import java.io.*; class Geeks { public static void main(String[] args) { // Getting the current root directory String root = System.getProperty("user.dir"); System.out.println("Current root directory: " + root); // Adding the file name to the root directory String path = root + "\\message.txt"; System.out.println("File path: " + path); // Reading the file from the path in the local directory FileReader f = new FileReader(path); // Creating an object as one of the ways of taking input BufferedReader b = new BufferedReader(f); // Printing the first 3 lines of the file "C:\user\message.txt" for (int counter = 0; counter < 3; counter++) System.out.println(b.readLine()); // Closing file connections // using the close() method f.close(); } } Output: To fix the above program, we either need to specify a list of exceptions using throws, or we need to use a try-catch block. We have used throws in the below program. Since FileNotFoundException is a subclass of IOException, we can just specify IOException in the throws list and make the above program compiler-error-free.Example: Java // Handling Checked Exceptions import java.io.*; class Geeks { public static void main(String[] args) throws IOException { // Getting the current root directory String root = System.getProperty("user.dir"); System.out.println("Current root directory: " + root); // Adding the file name to the root directory String path = root + "\\message.txt"; System.out.println("File path: " + path); // Reading the file from the path in the local directory try { FileReader f = new FileReader(path); // Creating an object as one of the ways of taking input BufferedReader b = new BufferedReader(f); // Printing the first 3 lines of the file // "C:\\Devanshu\\JAVACODES\\message.txt" for (int counter = 0; counter < 3; counter++) System.out.println(b.readLine()); // Closing file connections // using the close() method f.close(); } catch (FileNotFoundException e) { System.out.println("File not found: " + e.getMessage()); } catch (IOException e) { System.out.println("An I/O error occurred: " + e.getMessage()); } } } Output: Note: If you are running this code on Linux/macOS, use the correct path format i.e. /home/user/test/a.txtExplanation: In the above program we create a Java programme which reads a file from the same directory this programme may throw exceptions like FileNotFoundException or IOException so we handle it using the try-catch block to handle the exceptions and execute the programme without any interruption.Unchecked Exceptions in JavaUnchecked exception are exceptions that are not checked at the compile time. In Java, exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked. Consider the following Java program. It compiles fine, but it throws an ArithmeticException when run. The compiler allows it to compile because ArithmeticException is an unchecked exception.Example: Java program to illustrate the Runtime Unchecked Exception. Java // Java Program to Illustrate Un-checked Exceptions class Geeks { 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 x = 0; int y = 10; int z = y / x; } } Output: Note:Unchecked exceptions are runtime exceptions that are not required to be caught or declared in a throws clause. These exceptions are caused by programming errors, such as attempting to access an index out of bounds in an array or attempting to divide by zero.Unchecked exceptions include all subclasses of the RuntimeException class, as well as the Error class and its subclasses.The separation into checked and unchecked exceptions sounded like a good idea at the time. Over the years, it has introduced more boilerplate and less aesthetically pleasing code patterns than it solved real problems. The typical pattern within the Java ecosystem is to hide the checked exception within an unchecked one.Example:try {// Some I/O operation here} catch( final IOException ex ) {throw new RuntimeException( "I/O operation failed", ex );} Comment More infoAdvertise with us Next Article Java Try Catch Block K kartik Follow Improve Article Tags : Java Difference Between Java-Exceptions Practice Tags : Java Similar Reads Basics of JavaLearn Java - A Beginners Guide for 2024If you are new to the world of coding and want to start your coding journey with Java, then this learn Java a beginners guide gives you a complete overview of how to start Java programming. Java is among the most popular and widely used programming languages and platforms. A platform is an environme10 min readIntroduction to JavaJava is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It is platform-independent, which means we can write code once and run it anywhere using the Java Virtual Machine (JVM). Java is mostly used for building desktop applications, web applications, Android4 min readSimilarities and Difference between Java and C++Nowadays Java and C++ programming languages are vastly used in competitive coding. Due to some awesome features, these two programming languages are widely used in industries as well as competitive programming. C++ is a widely popular language among coders for its efficiency, high speed, and dynamic6 min readSetting up Environment Variables For Java - Complete Guide to Set JAVA_HOMEIn the journey to learning the Java programming language, setting up environment variables for Java is essential because it helps the system locate the Java tools needed to run the Java programs. Now, this guide on how to setting up environment variables for Java is a one-place solution for Mac, Win6 min readJava SyntaxJava is an object-oriented programming language that is known for its simplicity, portability, and robustness. The syntax of Java programming language is very closely aligned with C and C++, which makes it easier to understand. Java Syntax refers to a set of rules that define how Java programs are w6 min readJava Hello World ProgramJava is one of the most popular and widely used programming languages and platforms. In this article, we will learn how to write a simple Java Program. This article will guide you on how to write, compile, and run your first Java program. With the help of Java, we can develop web and mobile applicat6 min readDifferences Between JDK, JRE and JVMUnderstanding the difference between JDK, JRE, and JVM plays a vital role in understanding how Java works and how each component contributes to the development and execution of Java applications. The main difference between JDK, JRE, and JVM is:JDK: JDK stands for Java Development Kit. It is a set o4 min readHow JVM Works - JVM ArchitectureJVM (Java Virtual Machine) runs Java applications as a run-time engine. JVM is the one that calls the main method present in a Java code. JVM is a part of JRE (Java Runtime Environment). Java applications are called WORA (Write Once Run Anywhere). This means a programmer can develop Java code on one7 min readJava IdentifiersAn identifier in Java is the name given to Variables, Classes, Methods, Packages, Interfaces, etc. These are the unique names used to identify programming elements. Every Java Variable must be identified with a unique name.Example:public class Test{ public static void main(String[] args) { int a = 22 min readVariables & DataTypes in JavaJava VariablesIn Java, variables are containers that store data in memory. Understanding variables plays a very important role as it defines how data is stored, accessed, and manipulated.Key Components of Variables in Java:A variable in Java has three components, which are listed below:Data Type: Defines the kind9 min readScope of Variables in JavaThe scope of variables is the part of the program where the variable is accessible. Like C/C++, in Java, all identifiers are lexically (or statically) scoped, i.e., scope of a variable can be determined at compile time and independent of the function call stack. In this article, we will learn about7 min readJava Data TypesJava is statically typed and also a strongly typed language because each type of data, such as integer, character, hexadecimal, packed decimal etc. is predefined as part of the programming language, and all constants or variables defined for a given program must be declared with the specific data ty14 min readOperators in JavaJava OperatorsJava operators are special symbols that perform operations on variables or values. These operators are essential in programming as they allow you to manipulate data efficiently. They can be classified into different categories based on their functionality. In this article, we will explore different15 min readJava Arithmetic Operators with ExamplesOperators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they6 min readJava Assignment Operators with ExamplesOperators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they7 min readJava Unary Operator with ExamplesOperators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions be it logical, arithmetic, relational, etc. They are classified based on the functionality they p8 min readJava Relational Operators with ExamplesOperators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they10 min readJava Logical Operators with ExamplesLogical operators are used to perform logical "AND", "OR", and "NOT" operations, i.e., the functions similar to AND gate and OR gate in digital electronics. They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition under particular consider8 min readJava Ternary OperatorOperators constitute the basic building block of any programming language. Java provides many types of operators that can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provi5 min readBitwise Operators in JavaIn Java, Operators are special symbols that perform specific operations on one or more than one operands. They build the foundation for any type of calculation or logic in programming.There are so many operators in Java, among all, bitwise operators are used to perform operations at the bit level. T6 min readPackages in JavaJava PackagesPackages in Java are a mechanism that encapsulates a group of classes, sub-packages, and interfaces. Packages are used for: Prevent naming conflicts by allowing classes with the same name to exist in different packages, like college.staff.cse.Employee and college.staff.ee.Employee.They make it easie8 min readFlow Control in JavaDecision Making in Java (if, if-else, switch, break, continue, jump)Decision-making statements in Java execute a block of code based on a condition. Decision-making in programming is similar to decision-making in real life. In programming, we also face situations where we want a certain block of code to be executed when some condition is fulfilled.A programming lang10 min readJava if statementThe Java if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e. if a certain condition is true then a block of statements is executed otherwise not.Example:Java// Java program to illustrate If st5 min readJava if-else StatementThe if-else statement in Java is a powerful decision-making tool used to control the program's flow based on conditions. It executes one block of code if a condition is true and another block if the condition is false. In this article, we will learn Java if-else statement with examples.Example:Java/3 min readJava if-else-if ladder with ExamplesThe Java if-else-if ladder is used to evaluate multiple conditions sequentially. It allows a program to check several conditions and execute the block of code associated with the first true condition. If none of the conditions are true, an optional else block can execute as a fallback.Example: The b3 min readLoops in JavaJava LoopsLoops in programming allow a set of instructions to run multiple times based on a condition. In Java, there are three types of loops, each with its own syntax and method of checking the condition, but fundamentally, they all serve the same purpose.Loops in JavaIn Java, there are three types of Loops7 min readJava For LoopJava for loop is a control flow statement that allows code to be executed repeatedly based on a given condition. The for loop in Java provides an efficient way to iterate over a range of values, execute code multiple times, or traverse arrays and collections.Now let's go through a simple Java for lo4 min readJava while LoopJava while loop is a control flow statement used to execute the block of statements repeatedly until the given condition evaluates to false. Once the condition becomes false, the line immediately after the loop in the program is executed.Let's go through a simple example of a Java while loop:Javapub3 min readJava Do While LoopJava do-while loop is an Exit control loop. Unlike for or while loop, a do-while check for the condition after executing the statements of the loop body.Example:Java// Java program to show the use of do while loop public class GFG { public static void main(String[] args) { int c = 1; // Using do-whi4 min readFor-Each Loop in JavaThe for-each loop in Java (also called the enhanced for loop) was introduced in Java 5 to simplify iteration over arrays and collections. It is cleaner and more readable than the traditional for loop and is commonly used when the exact index of an element is not required.Example: Using a for-each lo8 min readJump Statements in JavaJava Continue StatementIn Java, the continue statement is used inside the loops such as for, while, and do-while to skip the current iteration and move directly to the next iteration of the loop.Example:Java// Java Program to illustrate the use of continue statement public class Geeks { public static void main(String args4 min readJava Break StatementThe Break Statement in Java is a control flow statement used to terminate loops and switch cases. As soon as the break statement is encountered from within a loop, the loop iterations stop there, and control returns from the loop immediately to the first statement after the loop. Example:Java// Java3 min readJava return Keywordreturn keyword in Java is a reserved keyword which is used to exit from a method, with or without a value. The usage of the return keyword can be categorized into two cases:Methods returning a valueMethods not returning a value1. Methods Returning a ValueFor the methods that define a return type, th4 min readArrays in JavaArrays in JavaArrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me15+ min readJava Multi-Dimensional ArraysMultidimensional arrays are used to store the data in rows and columns, where each row can represent another individual array are multidimensional array. It is also known as array of arrays. The multidimensional array has more than one dimension, where each row is stored in the heap independently. T10 min readJagged Array in JavaIn Java, a Jagged array is an array that holds other arrays. When we work with a jagged array, one thing to keep in mind is that the inner array can be of different lengths. It is like a 2D array, but each row can have a different number of elements.Example:arr [][]= { {10,20}, {30,40,50,60},{70,80,6 min readStrings in JavaJava StringsIn Java, a String is the type of object that can store a sequence of characters enclosed by double quotes, and every character is stored in 16 bits, i.e., using UTF 16-bit encoding. A string acts the same as an array of characters. Java provides a robust and flexible API for handling strings, allowi9 min readString Class in JavaA string is a sequence of characters. In Java, objects of the String class are immutable, which means they cannot be changed once created. In this article, we are going to learn about the String class in Java.Example of String Class in Java:Java// Java Program to Create a String import java.io.*; cl7 min readStringBuffer Class in JavaThe StringBuffer class in Java represents a sequence of characters that can be modified, which means we can change the content of the StringBuffer without creating a new object every time. It represents a mutable sequence of characters.Features of StringBuffer ClassThe key features of StringBuffer c11 min readJava StringBuilder ClassIn Java, the StringBuilder class is a part of the java.lang package that provides a mutable sequence of characters. Unlike String (which is immutable), StringBuilder allows in-place modifications, making it memory-efficient and faster for frequent string operations.Declaration:StringBuilder sb = new7 min readOOPS in JavaJava OOP(Object Oriented Programming) ConceptsJava Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,13 min readClasses and Objects in JavaIn Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior, or in other words, we can say that a class is a blueprint for objects, wh11 min readJava MethodsJava Methods are blocks of code that perform a specific task. A method allows us to reuse code, improving both efficiency and organization. All methods in Java must belong to a class. Methods are similar to functions and expose the behavior of objects.Example: Java program to demonstrate how to crea8 min readAccess Modifiers in JavaIn Java, access modifiers are essential tools that define how the members of a class, like variables, methods, and even the class itself can be accessed from other parts of our program. They are an important part of building secure and modular code when designing large applications. Understanding de7 min readWrapper Classes in JavaA Wrapper class in Java is one whose object wraps or contains primitive data types. When we create an object in a wrapper class, it contains a field, and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object. Let's check on the wr6 min readNeed of Wrapper Classes in JavaFirstly the question that hits the programmers is when we have primitive data types then why does there arise a need for the concept of wrapper classes in java. It is because of the additional features being there in the Wrapper class over the primitive data types when it comes to usage. These metho3 min read Like