In this Java exceptions tutorial, learn what is an exception in Java, the difference between a checked exception and an unchecked exception. We will also learn some Java exception handling best practices. Show
1. What is Exception in Java?
A few examples of an exception in the program execution can be:
2. Handling a Thrown ExceptionWe have two choices when an exception object is created in our application;
This is a very important decision to be made while setting the responsibilities of a method. A method should clearly indicate that what all exceptions it will handle and which it will not. It is defined in the method declaration using the throws keyword. To handle the exception, We must catch the exception in catch section of try-catch block. try { //code } catch(Exception e) { //handle exception }
3. Checked Exception vs Unchecked Exception3.1. Exception HierarchyIn Java, exceptions are broadly categorized into two sections:
3.2. Checked ExceptionsJava checked exceptions are those exceptions, as the name suggests, which a method must handle in its body or throw to the caller method so the caller method can handle it.
Java compiler forces us to handle these exceptions in some manner in the application code. We must handle these exceptions at a suitable level inside the application so that we can inform the user about the failure and ask him to retry or come later. Generally, checked exceptions denote error scenarios that are outside the immediate control of the program. These occur usually interacting with other systems/network resources e.g. database errors, network connection errors, missing files, etc. Note that all checked exceptions are subclasses of Exception class. For example,
Checked Exception ExampleFileNotFoundException is a checked exception in Java. Anytime, we want to read a file from the filesystem, Java forces us to handle an error situation where the file may not be present in the place. public static void main(String[] args) { FileReader file = new FileReader("somefile.txt"); }In the above example, you will get compile-time error with the message – Unhandled exception type FileNotFoundException. To make the program able to compile, we must handle this error situation in the try-catch block. Below given code will compile absolutely fine. public static void main(String[] args) { try { FileReader file = new FileReader("somefile.txt"); } catch (FileNotFoundException e) { //Alternate logic e.printStackTrace(); } }3.3. Unchecked Exception
Unchecked exceptions will come into life and occur in the program, once any buggy code is executed. In Java, a member method is not forced by the compiler to declare the unchecked exceptions into the method declaration. Generally, such methods almost always do not declare them. Unchecked Exceptions are subclasses of RuntimeException class.
Unchecked Exception ExampleThe code in the given program does not give any compile-time error. But when we run the example, it throws NullPointerException. NullPointerException is an unchecked exception in Java. public static void main(String[] args) { try { FileReader file = new FileReader("pom.xml"); file = null; file.read(); } catch (IOException e) { //Alternate logic e.printStackTrace(); } }3. Exception Handling Best Practices
In reality, most applications will have to recover from pretty much all exceptions including NullPointerException, IllegalArgumentExceptions and many other unchecked exceptions. The action/transaction that failed will be aborted but the application has to stay alive and be ready to serve the next action/transaction. The only time it is normally legal to shut down an application is during startup. For example, if a configuration file is missing and the application cannot do anything sensible without it, then it is legal to shut down the application. 4. ConclusionIn this Java tutorial, we learned about Java exceptions. We learned the difference between checked vs unchecked exceptions in Java, along with how to handle unchecked exceptions, exception hierarchy in Java with examples. Remember the biggest difference between checked and unchecked exceptions is that checked exceptions are forced by the compiler and used to indicate exceptional conditions that are out of the control of the program, while unchecked exceptions are occurred during runtime and are used to indicate programming errors. Happy Learning !!
There are two types of exceptions: checked exception and unchecked exception. In this guide, we will discuss them. The main difference between checked and unchecked exception is that the checked exceptions are checked at compile-time while unchecked exceptions are checked at runtime. What are checked exceptions?Checked exceptions are checked at compile-time. It means if a method is throwing a checked exception then it should handle the exception using try-catch block or it should declare the exception using throws keyword, otherwise the program will give a compilation error. Lets understand this with the help of an example: Checked Exception ExampleIn this example we are reading the file myfile.txt and displaying its content on the screen. In this program there are three places where a checked exception is thrown as mentioned in the comments below. FileInputStream which is used for specifying the file path and name, throws FileNotFoundException. The read() method which reads the file content throws IOException and the close() method which closes the file input stream also throws IOException. import java.io.*; class Example { public static void main(String args[]) { FileInputStream fis = null; /*This constructor FileInputStream(File filename) * throws FileNotFoundException which is a checked * exception */ fis = new FileInputStream("B:/myfile.txt"); int k; /* Method read() of FileInputStream class also throws * a checked exception: IOException */ while(( k = fis.read() ) != -1) { System.out.print((char)k); } /*The method close() closes the file input stream * It throws IOException*/ fis.close(); } }Output: Exception in thread "main" java.lang.Error: Unresolved compilation problems: Unhandled exception type FileNotFoundException Unhandled exception type IOException Unhandled exception type IOExceptionWhy this compilation error? As I mentioned in the beginning that checked exceptions gets checked during compile time. Since we didn’t handled/declared the exceptions, our program gave the compilation error. Method 1: Declare the exception using throws keyword. Output: Method 2: Handle them using try-catch blocks. This code will run fine and will display the file content. Here are the few other Checked Exceptions –
What are Unchecked exceptions?Unchecked exceptions are not checked at compile time. It means if your program is throwing an unchecked exception and even if you didn’t handle/declare that exception, the program won’t give a compilation error. Most of the times these exception occurs due to the bad data provided by user during the user-program interaction. It is up to the programmer to judge the conditions in advance, that can cause such exceptions and handle them appropriately. All Unchecked exceptions are direct sub classes of RuntimeException class. Lets understand this with an example: Unchecked Exception Exampleclass Example { public static void main(String args[]) { int num1=10; int num2=0; /*Since I'm dividing an integer with 0 * it should throw ArithmeticException */ int res=num1/num2; System.out.println(res); } }If you compile this code, it would compile successfully however when you will run it, it would throw ArithmeticException. That clearly shows that unchecked exceptions are not checked at compile-time, they occurs at runtime. Lets see another example. class Example { public static void main(String args[]) { int arr[] ={1,2,3,4,5}; /* My array has only 5 elements but we are trying to * display the value of 8th element. It should throw * ArrayIndexOutOfBoundsException */ System.out.println(arr[7]); } }This code would also compile successfully since ArrayIndexOutOfBoundsException is also an unchecked exception. Output: The specified index does not exist in array. Please correct the error.Here are the few unchecked exception classes:
|