Exception handling and create user defined exceptions

What is an exception?
An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.

What is exception handling?
  • Exception Handling is the mechanism to handle run-time malfunctions. 
  • We need to handle such exceptions to prevent abrupt termination of program. 
  • The term exception means exceptional condition, it is a problem that may arise during the execution of program. 
  • A bunch of things can lead to exceptions, including programmer error, hardware failures, files that need to be opened cannot be found, resource exhaustion etc.
Exception handeling
Exception are categorized into 3 category.
Java Exception Handling
1. Checked Exception:
Compiler checks exceptions during compilation to see whether the programmer has handled them or not. If these exceptions are not handled/declared in the program, you will get compilation error. 

Example : File that need to be opened is not found. These type of exceptions must be checked at compile time.

2. Unchecked Exceptions: 
Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked at compile-time so compiler does not check whether the programmer has handled them or not but it’s the responsibility of the programmer to handle these exceptions and provide a safe exit.

Example: ArithmeticException, NullPointerException, Array Index out of Bound exception. Unchecked exceptions are checked at runtime.

3) Error:
Errors are exceptional scenarios that are out of scope of application and it’s not possible to anticipate and recover from them.

Examplehardware failure, JVM crash or out of memory error. 

Exception handling is done using five keywords,
  1. try
  2. catch
  3. throw
  4. throws
  5. finally
1) Using try and catch:
  1. Try is used to guard a block of code in which exception may occur. This block of code is called guarded region. 
  2. A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in guarded code, the catch block that follows the try is checked, if the type of exception that occured is listed in the catch block then the exception is handed over to the catch block which then handles it.
Example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class ExceptionDemo{
 public static void main(String args[]){
  int a, b, c;
  try{
   a = 0;
   b = 10;
   c = b / a;
   System.out.println("This line will not be executed");
  } catch (ArithmeticException e){
   System.out.println("Divided by zero");
  }
  System.out.println("After exception is handled");
 }
}

Output :
Divided by zero
After exception is handled


An exception will thrown by this program as we are trying to divide a number by zero inside try block. The program control is transferred outside try block. Thus the line "This line will not be executed" is never parsed by the compiler. The exception thrown is handle in catch block. Once the exception is handled the program controls continue with the next line in the program. Thus the line "After exception is handled" is printed.

Note: Always use try catch block to log your exception in selenium webdriver reports.

2) Multiple catch blocks:
  1. A try block can be followed by multiple catch blocks. 
  2. You can have any number of catch blocks after a single try block.
  3. If an exception occurs in the guarded code the exception is passed to the first catch block in the list. 
  4. If the exception type of exception, matches with the first catch block it gets caught, if not the exception is passed down to the next catch block. 
  5. This continue until the exception is caught or falls through all catches.
Example :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class ExceptionDemo {
 public static void main(String[] args) {
  try {
   int arr[] = { 1, 2 };
   arr[2] = 3 / 0;
  } catch (ArithmeticException ae) {
   System.out.println("divide by zero");
  } catch (ArrayIndexOutOfBoundsException e) {
   System.out.println("array index out of bound exception");
  }
 }
}
Output :
divide by zero

3) The Throws/Throw Keywords
  1. throw keyword is used to throw an exception explicitly. 
  2. Only object of Throwable class or its sub classes can be thrown. 
  3. Program execution stops on encountering throw statement, and the closest catch statement is checked for matching type of exception.
Example :

1
2
3
4
5
6
7
8
9
class Test{
 static void average(){
  try{
    throw new ArithmeticException("demo");
  }catch(ArithmeticException e){
   System.out.println("Exception caught");
  }
 }
}

Any method can cause exceptions, it should list all the exceptions possible during its execution, so that anyone calling that method gets a prior knowledge about which exceptions are to be handled.  A method can do so by using the throws keyword.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Test {
 static void check() throws ArithmeticException {
  throw new ArithmeticException("demo");
 }

 public static void main(String args[]) {
  try {
   check();
  } catch (ArithmeticException e) {
   System.out.println("caught" + e);
  }
 }
}

4) Finally Block
  1. A finally block of code always executed, irrespective of occurrence of an Exception.
  2. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.
Example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class FinallyBlockDemo{
 public static void main(String[] args){
  int a[] = new int[2];
  try{
   System.out.println("Access invalid element" + a[3]);
  }finally{
   System.out.println("finally is always executed.");
  }
 }
}

Output:
finally is always executed. 
Exception in thread main java. Lang. exception array Index out of bound exception. 

All these concepts about exceptions and ways of handling them will helps you in your webdriver test exception handling.


Java Exception Flow
User Defined Exceptions

In user defined Exception we create our own exception class and throws that exception using ‘throw’ keyword. This can be done by extending the class Exception.

Using custom exception, you can define your own exception and message.

Let's see a simple example of java custom exception.

Example 1:
1
2
3
4
5
6
7
//A Class that represents use-defined exception
class MyException extends Exception{
 public MyException(String s){
  // Call constructor of parent Exception
  super(s);
 }
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// A Class that uses above MyException
public class TestClass
{
 // Driver Program
 public static void main(String args[]){
  try{
   // Throw an object of user defined exception
   throw new MyException("Throwing my exception");
  }catch (MyException ex){
   System.out.println("Caught");

   // Print the message from MyException object
   System.out.println(ex.getMessage());
  }
 }
}
Output:
Caught
Throwing my exception







In above code, constructor of MyException requires a string as its argument. 
The string is passed to parent class Exception’s constructor using super().  
The constructor of Exception class can also be called without a parameter and 
call to super is not mandatory.


Example 2:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public class MyException extends Exception {
 String str1;
 MyException(String str2) {
  str1 = str2;
 }

 public String toString() {
  return ("User defined Exception: " + str1);
 }
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Example1 {
 public static void main(String args[]) {
  try {
   // I'm throwing the custom exception using throw
   throw new MyException("Throwing the custom exception using throw");
  } catch (MyException exp) {
   System.out.println(exp);
  }
 }
}

In above code, constructor of MyException requires a string as its argument.
System.out.println(excep); is executed as we are passing Object type to
println() so toString() method is called, here we have overrided the toString()
so we get the output:
User defined Exception: Throwing the custom exception using throw.

<-- Previous || Next -->

3 comments:

  1. Thanks Vinod Sir !! This page explains Exception handling in very detail with good examples.

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete
  3. This comment has been removed by a blog administrator.

    ReplyDelete