# 1) Introduction to Exception Handling

**Exception Handling**
----------------------

The process of converting system error messages into user friendly error message is known as **Exception handling**. This is one of the powerful features of Java to handle run time error and maintain normal flow of java application.

### **Exception**

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

### Types of exceptions

There are two types of exceptions in Java:\
&#x20;1\)Checked exceptions\
&#x20;2\)Unchecked exceptions

#### Checked exceptions

All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks them 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. For example, SQLException, IOException, ClassNotFoundException etc.

#### 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. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.

### **Why use Exception Handling**

Handling the exception is nothing but converting system error generated message into user friendly error message in others word whenever an exception occurs in the java application, JVM will create an object of appropriate exception of sub class and generates system error message, these system generated messages are not understandable by user so need to convert it into user-friendly error message. You can convert system error message into user-friendly error message by using exception handling feature of java.

There are five keywords for Handling the Exception

·         Try

·         Catch

·         Finally

·         Throw

·         throws

Syntax for handling the exception

![](https://2172743581-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La4k4liN--SZ6ay4iod%2F-LaYvdMU_emZ2ihQbnvN%2F-LaYwEJKE6EuCPAefaeO%2Fimage.png?alt=media\&token=50a820af-5b62-465c-84c5-d240b1e79b58)



### **Example without Exception Handling:**

```java
public class ExceptionHandling {
	public static void main(String[] args) {
		int a=10, b=0;
		b=a/0;
		System.out.println("===Ececuted this Line===");                              
	}
}
```

![](https://2172743581-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La4k4liN--SZ6ay4iod%2F-LaYvdMU_emZ2ihQbnvN%2F-LaYw_X_6U4DB7EDee4I%2Fimage.png?alt=media\&token=79bbab4e-1a43-4ac2-96ad-81cd1c96ac6f)

As you observe, Abnormally terminate program and give a message like above, this error message is not understandable by user so we convert this error message into user friendly error message, like "**denominator not be zero**".

### **Example of Exception Handling:**

```java
public class ExceptionHandling {

	public static void main(String[] args) {
		int a=10, b=0;
		try
		{
		b=a/0;
		}
		catch (Exception e)
		{
		System.out.println("Denominator not be zero");
		}            
                          
	}
}
```

![](https://2172743581-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La4k4liN--SZ6ay4iod%2F-LaYvdMU_emZ2ihQbnvN%2F-LaYwp6ATFFNywEOm-S1%2Fimage.png?alt=media\&token=4f930852-638c-437a-b51d-fdb3219585f1)

### **try Block:**

Inside try block we write the block of statements which causes executions at run time in other words try block always contains problematic statements.

**Important points about try block**

·         If any exception occurs in try block then CPU controls comes out to the try block and executes appropriate catch block.

·         After executing appropriate catch block, even though we use run time statement, CPU control never goes to try block to execute the rest of the statements.

·         Each and every try block must be immediately followed by catch block that is no intermediate statements are allowed between try and catch block.

![](https://2172743581-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La4k4liN--SZ6ay4iod%2F-LaYvdMU_emZ2ihQbnvN%2F-LaYy0COwYf9s4QO3axH%2Fimage.png?alt=media\&token=58757005-beee-484f-801b-d323b315d293)

·         Each and every **try** block must contain at least one **catch** block. But it is highly recommended to write multiple catch blocks for generating multiple user friendly error messages. One try block can contains another try block that is nested or inner try block can be possible.

### **catch block:**

Inside catch block we write the block of statements which will generates user friendly error messages.

**Catch block important points**

Catch block will execute exception occurs in try block.

You can write multiple catch blocks for generating multiple user friendly error messages to make your application strong.

**Multiple catch block:**

You can write multiple catch blocks for generating multiple user friendly error messages to make your application strong. You can see below example.

```java
import java.util.*;

public class ExceptionDemo {
	public static void main(String[] args) {
		int a, b, ans = 0;
		Scanner s = new Scanner(System.in);
		System.out.println("Enter any two numbers: ");
		try {
			a = s.nextInt();

			b = s.nextInt();

			ans = a / b;

			System.out.println("Result: " + ans);
		} catch (ArithmeticException ae) {
			System.out.println("Denominator not be zero");
		}

		catch (Exception e) {
			System.out.println("Enter valid number");
		}
	}
}
```

![](https://2172743581-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La4k4liN--SZ6ay4iod%2F-LaYvdMU_emZ2ihQbnvN%2F-LaYylFflo3UjnEMigzN%2Fimage.png?alt=media\&token=0e06b876-66b5-42dd-a71e-818c7628ef1e)

### **finally block:**

It is a block that is used to execute important code such as closing connection, stream etc.

Java finally block is always executed whether exception is handled or not.

Java finally block must be followed by try or catch block.

**Why use java finally**

Finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc.

**Usage of Java finally**

```java
class TestFinallyBlock {
	public static void main(String args[]) {
		try {
			int data = 25 / 5;
			System.out.println(data);
		} catch (NullPointerException e) {
			System.out.println(e);
		} finally {
			System.out.println("finally block");
		}
		System.out.println("rest of the code");
	}
}
```

![](https://2172743581-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La4k4liN--SZ6ay4iod%2F-LaYvdMU_emZ2ihQbnvN%2F-LaYz7ozITVIK71oFtn6%2Fimage.png?alt=media\&token=ff12f184-8228-4e2f-bb24-e91e55ceb8df)

**Way to skip finally block**

```java
public class Main {
    public static void main(String[] args) {
        try {
            System.out.println("Hi");
            System.exit(0);
        }
        finally {
            System.out.println("Bye!");
        }
    }
}
```

In the above code by calling system.exit in try block terminates the JVM due to wich finally block will not be executed.

### **throw keyword :**



```java
/* In this program we are checking the Student age
 * if the student age<12 and weight <40 then our program 
 * should return that the student is not eligible for registration.
 */
public class ThrowExample {
	static void checkEligibilty(int stuage, int stuweight) {
		if (stuage < 12 && stuweight < 40) {
			throw new ArithmeticException("Student is not eligible for registration");
		} else {
			System.out.println("Student Entry is Valid!!");
		}
	}

	public static void main(String args[]) {
		System.out.println("Welcome to the Registration process!!");
		try {
			checkEligibilty(10, 39);
		} catch (Exception e) {
			System.out.println(e);
		}
		System.out.println("Have a nice day..");
	}
}
```

![](https://2172743581-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La4k4liN--SZ6ay4iod%2F-LaZ0ug6_HSI2Ha_eYwh%2F-LaZ11RdlAL_U7N97tVr%2Fimage.png?alt=media\&token=3a1dd729-9b1f-4952-816c-6efeccd9d4bd)

### **throws keyword:**

As we know that there are two types of exception checked and unchecked. Checked exception (compile time) force you to handle them, if you don’t handle them then the program will not compile.\
&#x20;On the other hand unchecked exception (Runtime) doesn’t get checked during compilation. **Throws keyword** is used for handling checked exceptions. By using throws we can declare multiple exceptions in one go.

#### What is the need of having throws keyword when you can handle exception using try-catch?

Lets say we have a method myMethod() that has statements that can throw either ArithmeticException or NullPointerException, in this case you can use try-catch as shown below:

```java
public void myMethod()
{
  try {
    // Statements that might throw an exception 
  }
  catch (ArithmeticException e) {
    // Exception handling statements
  }
  catch (NullPointerException e) {
    // Exception handling statements
  }
}
```

But suppose you have several such methods that can cause exceptions, in that case it would be tedious to write these try-catch for each method. The code will become unnecessary long and will be less-readable.

One way to overcome this problem is by using throws like this: declare the exceptions in the method signature using throws and handle the exceptions where you are calling this method by using try-catch.\
&#x20;Another advantage of using this approach is that you will be forced to handle the exception when you call this method, all the exceptions that are declared using throws, must be handled where you are calling this method else you will get compilation error.

```java
public void myMethod() throws ArithmeticException, NullPointerException
{
  // Statements that might throw an exception 
}

public static void main(String args[]) { 
  try {
    myMethod();
  }
  catch (ArithmeticException e) {
    // Exception handling statements
  }
  catch (NullPointerException e) {
    // Exception handling statements
  }
}
```

#### Example of throws Keyword

In this example the method myMethod() is throwing two **checked exceptions** so we have declared these exceptions in the method signature using **throws** Keyword. If we do not declare these exceptions then the program will throw a compilation error.

```java
import java.io.*;

class ThrowExample {
	void myMethod(int num) throws IOException, ClassNotFoundException {
		if (num == 1)
			throw new IOException("IOException Occurred");
		else
			throw new ClassNotFoundException("ClassNotFoundException");
	}
}

public class Example1 {
	public static void main(String args[]) {
		try {
			ThrowExample obj = new ThrowExample();
			obj.myMethod(1);
		} catch (Exception ex) {
			System.out.println(ex);
		}
	}
}
```

![](https://2172743581-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La4k4liN--SZ6ay4iod%2F-LaZ2JvhxcC3uZJ1Z6dO%2F-LaZ2RltmyqtgxUiAOON%2Fimage.png?alt=media\&token=557a8f22-02f6-4407-8512-2c3fef4fc5fd)

