Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Exceptions in Java

Instructor: Muhammad Ahmad Nawaz

What is an Exception?
An exception is an unwanted or unexpected event, which occurs during the execution of a program
i.e at run time, that disrupts the normal flow of the program’s instructions.
Error vs Exception
Error: An Error indicates serious problem that a reasonable application should not try to catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.

Exception Hierarchy
All exception and errors types are sub classes of class Throw able, which is base class of
hierarchy. One branch is headed by Exception. This class is used for exceptional conditions that
user programs should catch. NullPointerException is an example of such an exception. Another
branch, Error are used by the Java run-time system(JVM) to indicate errors having to do with the
run-time environment itself(JRE). StackOverflowError is an example of such an error.

For checked vs unchecked exception, see Checked vs Unchecked Exceptions


Types of Exception in Java with Examples

Java defines several types of exceptions that relate to its various class libraries. Java also allows
users to define their own exceptions.

Built-in Exceptions

Built-in exceptions are the exceptions which are available in Java libraries. These exceptions are
suitable to explain certain error situations. Below is the list of important built-in exceptions in
Java.
1. Arithmetic Exception
It is thrown when an exceptional condition has occurred in an arithmetic operation.

// Java program to demonstrate ArithmeticException


class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}
}
}
2. ArrayIndexOutOfBoundException
It is thrown to indicate that an array has been accessed with an illegal index. The index is
either negative or greater than or equal to the size of the array.
// Java program to demonstrate ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound_Demo
{
public static void main(String args[])
{
try{
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("Array Index is Out Of Bounds");
}
}
}
3. ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found
4. package main.java;
02
03 public class ClassNotFoundExceptionExample {
04
05 private static final String CLASS_TO_LOAD = "main.java.Utils";
06
07 public static void main(String[] args) {
08 try {
09 Class loadedClass = Class.forName(CLASS_TO_LOAD);
10 System.out.println("Class " + loadedClass + " found successfully!");
11 }
12 catch (ClassNotFoundException ex) {
13 System.err.println("A ClassNotFoundException was caught: " + ex.getMessage());
14 ex.printStackTrace();
15 }
16 }
17 }

5. FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
//Java program to demonstrate FileNotFoundException
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {

public static void main(String args[]) {


try {

// Following file does not exist


File file = new File("E://file.txt");

FileReader fr = new FileReader(file);


} catch (FileNotFoundException e) {
System.out.println("File does not exist");
}
}
}

6. IOException
It is thrown when an input-output operation failed or interrupted
7. InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some processing , and it is
interrupted.
8. NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
9. NoSuchMethodException
It is thrown when accessing a method which is not found.
10. NullPointerException
This exception is raised when referring to the members of a null object. Null represents
nothing
//Java program to demonstrate NullPointerException
class NullPointer_Demo
{
public static void main(String args[])
{
try {
String a = null; //null value
System.out.println(a.charAt(0));
} catch(NullPointerException e) {
System.out.println("NullPointerException..");
}
}
}
11. NumberFormatException
This exception is raised when a method could not convert a string into a numeric format.
// Java program to demonstrate NumberFormatException
class NumberFormat_Demo
{
public static void main(String args[])
{
try {
// "akki" is not a number
int num = Integer.parseInt ("akki") ;

System.out.println(num);
} catch(NumberFormatException e) {
System.out.println("Number format exception");
}
}
}
12. RuntimeException
This represents any exception which occurs during runtime.
13. StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative than the size
of the string
// Java program to demonstrate StringIndexOutOfBoundsException
class StringIndexOutOfBound_Demo
{
public static void main(String args[])
{
try {
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}
}
}
User-defined Custom Exception in Java

Java provides us facility to create our own exceptions which are basically derived classes
of Exception. For example MyException in below code extends the Exception class.
We pass the string to the constructor of the super class- Exception which is obtained using
“getMessage()” function on the object created.

// A Class that represents use-defined expception

class MyException extends Exception

public MyException(String s)

// Call constructor of parent Exception

super(s);

// A Class that uses above MyException

public class Main

// Driver Program

public static void main(String args[])

try

// Throw an object of user defined exception


throw new MyException("GeeksGeeks");

catch (MyException ex)

System.out.println("Caught");

// Print the message from MyException object

System.out.println(ex.getMessage());

}
In the 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.

// A Class that represents use-defined expception

class MyException extends Exception

// A Class that uses above MyException

public class setText

// Driver Program

public static void main(String args[])


{

try

// Throw an object of user defined exception

throw new MyException();

catch (MyException ex)

System.out.println("Caught");

System.out.println(ex.getMessage());

}
Example: To created a User-Defined Exception Class
class JavaException{
public static void main(String args[]){
try{
throw new MyException(2);
// throw is used to create a new exception and throw it.
}
catch(MyException e){
System.out.println(e) ;
}
}
}
class MyException extends Exception{
int a;
MyException(int b) {
a=b;
}
public String toString(){
return ("Exception Number = "+a) ; }}
ava finally block

Java finally block 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.

Case 1

Let's see the java finally example where exception doesn't occur.

1. class TestFinallyBlock{
2. public static void main(String args[]){
3. try{
4. int data=25/5;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }

Case 2

Let's see the java finally example where exception occurs and not handled.

1. class TestFinallyBlock1{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }

Case 3

Let's see the java finally example where exception occurs and handled.
1. public class TestFinallyBlock2{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(ArithmeticException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }

Nested try catch block in Java – Exception handling

When a try catch block is present in another try block then it is called the nested try catch block.
Each time a try block does not have a catch handler for a particular exception, then the catch blocks
of parent try block are inspected for that exception, if match is found that that catch block executes.

If neither catch block nor parent catch block handles exception then the system generated message
would be shown for the exception, similar to what we see when we don’t handle exception.

Lets see the syntax first then we will discuss this with an example.

Syntax of Nested try Catch

....
//Main try block
try {
statement 1;
statement 2;
//try-catch block inside another try block
try {
statement 3;
statement 4;
//try-catch block inside nested try block
try {
statement 5;
statement 6;
}
catch(Exception e2) {
//Exception Message
}
}
catch(Exception e1) {
//Exception Message
}

}
//Catch of Main(parent) try block
catch(Exception e3) {
//Exception Message
}
....
Nested Try Catch Example

Here we have deep (two level) nesting which means we have a try-catch block inside a nested try
block. To make you understand better I have given the names to each try block in comments like
try-block2, try-block3 etc.

This is how the structure is: try-block3 is inside try-block2 and try-block2 is inside main try-block,
you can say that the main try-block is a grand parent of the try-block3. Refer the explanation which
is given at the end of this code.

class NestingDemo{
public static void main(String args[]){
//main try-block
try{
//try-block2
try{
//try-block3
try{
int arr[]= {1,2,3,4};
/* I'm trying to display the value of
* an element which doesn't exist. The
* code should throw an exception
*/
System.out.println(arr[10]);
}catch(ArithmeticException e){
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block3");
}
}
catch(ArithmeticException e){
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block2");
}
}
catch(ArithmeticException e3){
System.out.print("Arithmetic Exception");
System.out.println(" handled in main try-block");
}
catch(ArrayIndexOutOfBoundsException e4){
System.out.print("ArrayIndexOutOfBoundsException");
System.out.println(" handled in main try-block");
}
catch(Exception e5){
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
}
}

s you can see that the ArrayIndexOutOfBoundsException occurred in the grand child try-block3.
Since try-block3 is not handling this exception, the control then gets transferred to the parent try-
block2 and looked for the catch handlers in try-block2. Since the try-block2 is also not handling
that exception, the control gets transferred to the main (grand parent) try-block where it found the
appropriate catch block for exception. This is how the the nesting structure works.

Example 2: Nested try block

class Nest{
public static void main(String args[]){
//Parent try block
try{
//Child try block1
try{
System.out.println("Inside block1");
int b =45/0;
System.out.println(b);
}
catch(ArithmeticException e1){
System.out.println("Exception: e1");
}
//Child try block2
try{
System.out.println("Inside block2");
int b =45/0;
System.out.println(b);
}
catch(ArrayIndexOutOfBoundsException e2){
System.out.println("Exception: e2");
}
System.out.println("Just other statement");
}
catch(ArithmeticException e3){
System.out.println("Arithmetic Exception");
System.out.println("Inside parent try catch block");
}
catch(ArrayIndexOutOfBoundsException e4){
System.out.println("ArrayIndexOutOfBoundsException");
System.out.println("Inside parent try catch block");
}
catch(Exception e5){
System.out.println("Exception");
System.out.println("Inside parent try catch block");
}
System.out.println("Next statement..");
}
}

In above example.
Block1: I have divided an integer by zero and it caused an ArithmeticException, since the catch
of block1 is handling ArithmeticException "Exception: e1" displayed.

Block2: In block2, ArithmeticException occurred but block 2 catch is only


handling ArrayIndexOutOfBoundsException so in this case control jump to the Main try-
catch(parent) body and checks for the ArithmeticException catch handler in parent catch blocks.
Since catch of parent try block is handling this exception using generic Exception handler that
handles all exceptions, the message “Inside parent try catch block” displayed as output.

Parent try Catch block: No exception occurred here so the “Next statement..” displayed.

The important point to note here is that whenever the child catch blocks are not handling any
exception, the jumps to the parent catch blocks, if the exception is not handled there as well then
the program will terminate abruptly showing system generated message.

Resources:
https://www.geeksforgeeks.org
https://www.javabrahman.com/corejava/newfeaturesjava7/catching-multiple-exception-types-in-
single-catch-block-in-java-7/
https://www.guru99.com/java-exception-handling.html
https://www.programmingsimplified.com/java/tutorial/java-exception-handling-tutorial
https://beginnersbook.com/2013/04/nested-try-catch/

You might also like