OOPs Concepts

Language Elements

Exceptions

Java String Class

Java Array Class

Collections

Java Example Codes

Core Java Interview Questions

Exceptions in Java


Exceptions are interruptions that occur during the normal execution of the program. Program processing get terminated, and control is trasferred to a special section of code called exception handler, printing a system generated message. Exceptions can occur at run time, as well during compilation of the program. Application itself can handle exceptions as they are mostly caused by errors in programming logic.

Some of the common exceptions include, opening a non-existing file, dividing by zero in an arithmetic expression, Network connection problem, values being manipulated are out of prescribed ranges etc.

There are certain type of problems which cannot be handled by the application itself, and they are called errors. Errors are not exceptions! Errors are conditions which are not caught by the normal execution of the program, e.g. memory error (OutOfMemoryError), hardware error etc. Unlike exeptions, errors are not recoverable.


  • Checked Exceptions

  • These are the exceptions which occur at the compile time. If they are not handled at compile time, system prints compilation error. Some common checked exceptions include, ClassNotFoundException, FileNotFoundException, IllegalAccessException, NoSuchFieldException etc.


  • Unchecked Exceptions

  • These are the exceptions which occur at run time. Compiler do not check them, but programmer need to make sure to handle these exceptions. Examples of these exceptions include, ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException, NegativeArraySizeException etc.


  • Exception Handling in Java

  • All exception classes are subtypes of the java.lang.Exception class and java.lang.Error describes the error. Both exceptions and error classes are derived from the Throwable class.

    An exception can be handled by putting try/catch block around the code that might generate an exception. If an exception occurs in the code within try block, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the program flow continues without interruption, otherwise exception must be specified using throws keyword.

    Followed by try block, the code in the finally block will always be executed whether or not an exception occurs. Cleanup code such as closing a file is put inside the finally block.





    Copyright © by Zafar Yasin. All rights reserved.