Skip to content

Latest commit

 

History

History
63 lines (46 loc) · 2.84 KB

Exception. Checked and Unchecked..md

File metadata and controls

63 lines (46 loc) · 2.84 KB

Exception. Checked vs Unchecked.

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

In Java, there are two types of exceptions: Checked and Unchecked.

Checked

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 using throws keyword.

Example:

private static void checkedExceptionWithThrows() throws FileNotFoundException {
    File file = new File("not_existing_file.txt");  
    FileInputStream stream = new FileInputStream(file);  
}

We can also use a try-catch block to handle a checked exception:

private static void checkedExceptionWithTryCatch() {
    File file = new File("not_existing_file.txt");
    try {
        FileInputStream stream = new FileInputStream(file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

Unchecked

An unchecked exception is an exception that occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation.

Example:

private static void divideByZero() {
    int numerator = 1;
    int denominator = 0;
    int result = numerator / denominator;
}

Here code will throw ArithmeticException at runtime, cause divide by 0.

Exception hierarchy

All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class.

Errors are abnormal conditions that happen in case of severe failures, these are not handled by the Java programs. Errors are generated to indicate errors generated by the runtime environment. Example: JVM is out of memory. Normally, programs cannot recover from errors.

The Exception class has two main subclasses: IOException class and RuntimeException Class.

Errors − These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

Links

https://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html
https://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/
https://www.baeldung.com/java-checked-unchecked-exceptions
https://www.tutorialspoint.com/java/java_exceptions.htm
https://www.javamex.com/tutorials/exceptions/exceptions_hierarchy.shtml