Skip to main content

Java Exception Handling

Java Exception Handling : try, catch, final

An exception is an event which that interrupts the normal flow of program. The exception could occur due to any resource required is not available, user enters invalid data , network connection lost etc.

When there is an anomaly during execution of the method, then that method creates an object which contains a lot of debugging information such as method hierarchy, line number where the exception occurred, type of exception etc. The method than pass this object to runtime system which is called throwing an exception.

When the exception is handover to runtime system then it tries to find some catch block which can handle this exception.  It tries to find the exception handler block from the method where the exception occurred and proceeds through the call stack in the reverse order in which the methods were called. When it find the block which can handle the type of exception then runtime system passes the exception object to the catch block. If no handler found then the runtime system terminates.


Exception Hierarchy : Throwable is the parent class which has two subclass : Exception and Error
Exceptions are further divided into checked exceptions and runtime exception. 











Errors: Errors are the exceptional scenarios which are not in the control of the programmer.
Errors are typically ignored in your code because you can rarely do anything about an error
For example  JVM crash, out of memory error, stack overflow.

Checked Exceptions: These are type of exception which we can anticipate and can handle, for example SQL Exception. These type of exception  requires being catches and handled during compile time. If Compiler doesn’t see try or catch block handling a Checked Exception, it throws Compilation error.
These exceptions do not extend RuntimeException class and must be handled to avoid a compile-time error by the programmer. All exception which are not subclass of Error or Runtime Exception, are checked exception.

Unchecked Exception :
The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException. Unchecked exceptions are not checked at compile-time rather they are checked at runtime. In case we are throwing any runtime exception in a method, it’s not required to specify them in the method signature throws clause. Runtime exceptions can be avoided with better programming.

Example
import java.io.*;
public class SampleException{

   public static void main(String args[]){
      try{
         int arry[] = new int[4];
         System.out.println("Access element Six :" + arry[5]);
      }catch(ArrayIndexOutOfBoundsException e){
         System.out.println("Accessed Element,Out of defined range    :" + e);
      }
      System.out.println("Out of the block");
   }
}

Exception Handling Keywords:

There are some specific keywords for exception handling in java.

* throw – It is used to throw exception to the runtime to handle it.
* throws – When we throw any exception in a method and not handling it, then we need to use throws keyword in method signature to make caller program aware about the possible exceptions that might be thrown by the method. The caller method might handle these exceptions or propagate it to it’s caller method using throws keyword. We can provide multiple exceptions in the throws clause.
Any Exception that can be thrown by a method is part of the method's public declaration. If any method call this method must handle the checked exception thrown by this method.

* try-catch – try-catch block is used for exception handling in the code. 'try' is the block where a code which may possibly throw exception is executed.
'catch'  is used after try block to handle the exceptions.
We can have multiple catch blocks with a try and try-catch block can be nested also.
We need to pass one parameter to catch block of type Exception.

*finally – It  is optional and can be used only with try-catch block.
It contains a set of statements that needs to be executed regardless of whether or not any exception occurs in try block.
The code present in the finally block executes even if the try or catch block contains control transfer statements like return, break or continue.


  • A try statement should have either catch block or finally block, it can have both blocks.
  • catch block must handle exception in the order that subclass is handled first
  • We can’t have catch or finally clause without a try statement. 
  • We can’t write any code between try-catch-finally block.
  • We can have multiple catch blocks with a single try statement.
  • There can be only one finally block, however there could be multiple catch block for a single try block

There could be any exception in the try block due to which the program flow will jump to catch block so few resources which were opened to use, might keep open.
But if we write those in the catch block, then there could be chance that exception does not occur or the exception occurred may not be of type that the catch block will handle.
If we write the same code in both try and catch that will be duplicate code.
SO we use finally block to write such code which must be executed in all the cases.

finally block may not get executed in case : 1)there is an exception in the finally block 2) System.exit() method is used


Exceptions Methods:

Following is the list of important methods available in the Throwable class.
SN Methods with Description
1 public String getMessage() Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.
2 public Throwable getCause() Returns the cause of the exception as represented by a Throwable object.
3 public String toString() Returns the name of the class concatenated with the result of getMessage()
4 public void printStackTrace() Prints the result of toString() along with the stack trace to System.err, the error output stream.
5 public StackTraceElement [] getStackTrace() Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.
6 public Throwable fillInStackTrace() Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.




CUSTOM EXCEPTIONS:

We can create our own exceptions too in java.  We can create exception corresponding to any condition which we feel that is not normal as per our application behaviour.
For example : We can create exception if the Mobile number entered is not in the format 
+CC xxx-yyy-zzzz


We should keep the following things in mind while planning our own exception type:


* Every exception/error  is child  of Throwable class
* If we want that the exception must be handled than we can extend the Exception class otherwise for unchecked exception we can extend the Runtime Class

Comments

Popular posts from this blog

OBJECT class in Java

OBJECT class in Java : Object is at the top of class hierarchy in java. Every class in the Java system is a descendent (direct or indirect) of the Object class. The Object class defines the basic state and behavior that all objects must have, such as the ability to compare oneself to another object, to convert to a string, to wait on a condition variable, to notify other objects that a condition variable has changed, and to return the object's class. Mainly below methods are provided by Object class : public String toString() returns the string representation of this object. protected Object clone() throws CloneNotSupportedException creates and returns the exact copy (clone) of this object. public boolean equals(Object obj) compares the given object to this object. public int hashCode() returns the hashcode number for this object. public final Class getClass() returns the Class class object of this object. The Class class can further be used to get the metadata of ...

Java Priority Queue sort using lambda expression

Priority Queue :     In Java  Priority Queue  is a  queue  which keeps its elements sorted as per their natural order( example in ascending orders for Integer, alphabetical a-z for alphabets) or using a custom Comparator at the time of creation you can custom sort it. It has most method  similar to a queue  add, clear, poll, peek As priority queue have to compare elements to keep in order so elements must be comparable otherwise, it will throw ClassCastException .  As null can not be compared so you are not allowed to insert null too A program to sort priority queue using Lambda function in Java           c lass   PriorityQueueLambdaJava { public List<Integer> KFrequent( int [] nums, int k) { Map<Integer, Integer> map = new HashMap<>(); for ( int j: nums) { map .put(j, map .getOrDefault(j, 0 ) + 1 ); } PriorityQueue<Map.Entry<Integ...

Important Keywords: Static, Continue,Break:

Important Keywords: Static, Continue,Break:  Static: The static keyword in java is used for memory management mainly.  The static keyword members belongs to the class rather than instance of the class. Following members can be declared as static: variable (also known as class variable) method (also known as class method) block nested class  static variables : We can use static keyword with a class level variable. A static variable is a class variable and doesn’t belong to Object/instance of the class. Since static variables are shared across all the instances of Object, they are not thread safe . Usually static variables are used with final keyword for common resources or constants that can be used by all the objects. If the static variable is not private, we can access it as: ClassName.variableName //static variable example private static int a ge; public static String name; static methods: A static method belongs t...