Tuesday, February 11, 2020

Exception Handling in Java

Exception Handling in Java

Error 

An error can not be handled by the programmer, they are out of control from the programmer.

  • Not enough space
  • Low Memory
  • No OS Support
  • Lack of h/w Support
  • Stack Overflow
  • Virtual Memory Error

Exception

An exception is an abnormal event that arises during the execution of the program and disrupts the normal flow of the program.

What does Exception handling mean? 

"What happens after an abnormality occurred?" is actually important.
If these exceptions are not handled properly, the program terminates abruptly and may cause severe consequences. For example, the network connections, database connections, and files may remain opened; database and file records may be left in an inconsistent state.

Handling Means

Suppose there are 10 statements in your program and there occurs an exception at statement 5, the rest of the code will not be executed i.e. only statements 1 to 4 will be executed and statements 6 to 10 will not be executed. If we perform exception handling, the rest of the statement will be executed. That is why we use exception handling in Java.
Java is an object-oriented programming language and almost everything belongs to a class. All of the Exceptions and Errors are the subclass of Throwable class.

throwable
All of the errors are subclasses are Error class and all of the exceptions are subclasses of the Exception class.  
Error class in Java
Exceptions are further divided into two categories,

  1. Compile-time exception or checked exception
  2. Runtime exception or unchecked exception

runtime and compile time Exception
Exception

Compile-time exception or checked exception


A checked exception is an exception due to an error situation that can be foreseen by the programmer. A checked exception must be handled by using a try-catch block or at least by using throws clause with that method. Non-compliance with this rule results in a compile-time error. For example, FileNotFoundException, SQLException


Runtime exception or unchecked exception

Class RuntimeException and all its subclasses are the unchecked exceptions. An unchecked exception is an exception that could have been avoided by the programmer. If there is a chance of unchecked exception than it is ignored by the compiler. For example NumberFormatException, NullPointerException,IndexOutOfBoundsException etc.
unchecked exception
Runtime Exception
The class hierarchy of Exception and Error classes
exception


Exception handling in java  can be done using five keyword
  1. try 
  2. catch
  3. throw
  4. throws
  5. finally

Video Tutorial