Checked vs Unchecked Exceptions in Java

Source: Internet
Author: User
Tags try catch

In short, Checked checks in the compile phase and must be handled using try catch or throws, such as FileNotFoundException.

Unchecked means that the compile phase will not be checked. For example, ArithmeticException Division (divided by 0)

 

 

 

In Java, there two types of exceptions:

1) Checked:Are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception usingThrowsKeyword.

For example, consider the following Java program that opens file at loginobn "C: esta.txt" and prints first three lines of it. the program doesn't compile, because the function main () uses FileReader () and FileReader () throws a checked exceptionFileNotFoundException. It also uses readLine () and close () methods, and these methods also throw checked exceptionIOException

 

import java.io.*; class Main {    public static void main(String[] args) {        FileReader file = new FileReader(C:\test\a.txt);        BufferedReader fileInput = new BufferedReader(file);                 // Print first 3 lines of file C:esta.txt        for (int counter = 0; counter < 3; counter++)             System.out.println(fileInput.readLine());                 fileInput.close();    }}


 

 

Output:

Exception in thread main java.lang.RuntimeException: Uncompilable source code - unreported exception java.io.FileNotFoundException; must be caught or declared to be thrownat Main.main(Main.java:5)

To fix the above program, we either need to specify list of exceptions using throws, or we need to use try-catch block. We have used throws in the below program. SinceFileNotFoundExceptionIs a subclassIOException, We can just specifyIOExceptionIn the throws list and make the above program compiler-error-free.

 

import java.io.*; class Main {    public static void main(String[] args) throws IOException {        FileReader file = new FileReader(C:\test\a.txt);        BufferedReader fileInput = new BufferedReader(file);                 // Print first 3 lines of file C:esta.txt        for (int counter = 0; counter < 3; counter++)             System.out.println(fileInput.readLine());                 fileInput.close();    }}


 

 

Output: First three lines of file "C: esta.txt"

2) UncheckedAre the exceptions that are not checked at compiled time. in C ++, all exceptions are unchecked, so it is not forced by the compiler to either handle or specify the exception. it is up to the programmers to be civilized, and specify or catch the exceptions.
In Java exceptions underErrorAndRuntimeExceptionClasses are unchecked exceptions, everything else under throwable is checked.

                   +-----------+   | Throwable |                   +-----------+                    /            /                     +-------+          +-----------+          | Error |          | Exception |          +-------+          +-----------+   /  |             / |                 ________/  ______/                     +------------------+unchecked checked| RuntimeException |+------------------+  /   |    |       _________________/      unchecked

Consider the following Java program. It compiles fine, but it throwsArithmeticExceptionWhen run. The compiler allows it to compile, becauseArithmeticExceptionIs an unchecked exception.

 

class Main {   public static void main(String args[]) {      int x = 0;      int y = 10;      int z = y/x;  }}


 

Output:

Exception in thread main java.lang.ArithmeticException: / by zeroat Main.main(Main.java:5)Java Result: 1

Why two types?
See Unchecked Exceptions-The Controversy for details.

Shocould we make our exceptions checked or unchecked?
Following is the bottom line from Java clients
If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.