0% found this document useful (0 votes)
26 views

OOP Through Java Unit - 3 - Exception Handling

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

OOP Through Java Unit - 3 - Exception Handling

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Exception Handling:

 Exception is an unwanted event that interrupts the normal flow of the program (or) runtime
error which will occurs during program execution
 If any error occurred, the remaining code will not execute and terminate the program
abnormally
 Exception handling allows us to handle the runtime errors caused by exceptions
 Used to raise an exception, handle an exception and avoiding abnormal termination of a
program
 We use 5 keywords in this i.e., try, catch, throw, throws, finally
 Exceptions are handled with the help of try and catch blocks
 Try and catch blocks are interrelated i.e., without try we can’t use catch and vice versa.
Hierarchy of Java Exception classes:

The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:

1
Types of Java Exceptions:
There are mainly two types of exceptions: checked and unchecked. An error is considered as the
unchecked exception. However, according to Oracle, there are three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error
1. Checked (Compile Time) Exception:
 The classes which directly inherit Throwable class except RuntimeException and Error
are known as checked exceptions
 Checked exceptions are checked at compile-time
 Ex: IOException, SQLException etc...
2. Unchecked (Run Time)Exception:
 The classes which inherit RuntimeException are known as unchecked exceptions
 Unchecked exceptions are not checked at compile-time, but they are checked at runtime
 Ex: ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException,
NumberFormatException etc…
3. Error
 Error is irrecoverable and it occurs due to problem with computer & software
 Ex: OutOfMemoryError, VirtualMachineError, AssertionError etc…
Java Exception Keywords:
Keyword Description
try "try" keyword is used to specify a block where we should place exception code
The try block must be followed by either catch or finally. It means, we can't use try block
alone
catch "catch" block is used to handle the exception
It must be preceded by try block which means we can't use catch block alone. It can be
followed by finally block later

finally "finally" block is used to execute the important code of the program
It is executed whether an exception is handled or not

throw "throw" keyword is used to throw an exception implicitly or explicitly from a method or
any block of code.

throws "throws" keyword is used to declare exceptions. It doesn't throw an exception


It specifies that there may occur an exception in the method & always used with method
signature.

2
Built-in exceptions:
1. ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found
2. FileNotFoundException
This Exception is raised when a file is not accessible or does not open
3. IOException
It is thrown when an input-output operation failed or interrupted
4. InterruptedException
It is thrown when a thread is waiting, sleeping or doing some processing and it is interrupted
5. ArithmeticException
It is thrown when an exceptional condition has occurred in an arithmetic operation
6. ArrayIndexOutOfBoundsException
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
7. NullPointerException
This exception is raised when referring to the members of a null object. Null represents nothing
8. NumberFormatException
This exception is raised when a method could not convert a string into a numeric format.
9. NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
10. NoSuchMethodException
It is thrown when accessing a method which is not found.
11. RuntimeException
This represents any exception which occurs during runtime.
12. StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative than the size of
the string

Java try-catch block:


 "try" keyword is used to specify a block where we should place exception code
 The try block must be followed by either catch or finally. It means, we can't use try block
alone

3
Syntax: Syntax:

try try
{ {
//code that may throw an exception //code that may throw an exception
} }
catch (Exception_class_Name ref) finally
{ {
// handle the exception // important code
} }

Example-1:
public class ExceptionHandlingDemo {

public static void main(String[] args) {

int x,y;
int a=10,b=5,c=5;
x=a/(b-c);
System.out.println(x);
y=a/(b+c);
System.out.println(y);
}
}

Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero

Example-2:
public class ExceptionHandlingDemo1 {
public static void main(String[] args) {
int x,y;
int a=10,b=5,c=5;
try
{
x=a/(b-c);
System.out.println(x);
}
catch (ArithmeticException e)
{
//System.out.println(e);
System.out.println("Exception handled");
}
y=a/(b+c);
System.out.println(y);
System.out.println("End of Try-Catch Block");
}
}

4
Output:
java.lang.ArithmeticException: / by zero
1
End of Try-Catch Block
Types of Unchecked (Run Time)Exceptions:
1. ArithmeticException  divide by zero
2. NullPointerException  sring str = null;
System.out.println(str.length()); ˟
3. NumberFormatException  sring str = “hello”;
int num = Integer.ParseInt(str); ˟
4. ArrayIndexOutOfBoundsException  int a[] = new int[5];
a[8] = 20; ˟
Java Multi-catch block:
A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.
Points to remember:
o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.

Example-3:
public class ExceptionHandlingDemo2 {
public static void main(String[] args) {
try
{
int x=10/0;
System.out.println(x);

int[] a=new int[5];


System.out.println(a[10]);

String b="REC";
int n= Integer.parseInt(b);

String c=null;
System.out.println(c.length());
}

catch (ArithmeticException e)
{
5
System.out.println(e);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
catch (NumberFormatException e)
{
System.out.println(e);
}
catch (NullPointerException e)
{
System.out.println(e);
}
System.out.println("End of the program");
}
}

Output:
java.lang.ArithmeticException: / by zero
End of the program
Example-4:
public class ExceptionHandlingDemo2 {
public static void main(String[] args) {
try
{
int x=10/0;
System.out.println(x);

int[] a=new int[5];


System.out.println(a[10]);

String b="REC";
int n= Integer.parseInt(b);

String c=null;
System.out.println(c.length());
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("End of Try-Catch Block");
}
}
Output:
java.lang.ArithmeticException: / by zero
End of the program

6
Java Nested try block:
In Java, using a try block inside another try block is permitted. It is called as nested try block.
For example, the inner try block can be used to handle ArithemeticException (division by zero)
While the outer try block can handle the ArrayIndexOutOfBoundsException.
Example:
public class NestedTry {
public static void main(String[] args) {
try
{
int a[]={10,0,30,40,50};
try
{
int b=a[3]/a[1];
}
catch(ArithmeticException e)
{
System.out.println(e);
}
a[5]=100;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
}
}

Output:
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5

7
Usage of Java finally:
"finally" block is used to execute the important code of the program. It is executed whether an
exception is handled or not
Syntax:
Syntax:
try
try
{
{
//code that may throw an exception
//code that may throw an exception
}
}
catch (Exception_class_Name ref)
finally
{
{
// handle the exception
// important code
}
}
finally
{
// important code
}

Example -1: When an exception does not occur

public class FinallyDemo {


public static void main(String[] args) {
int x,y;
int a=10,b=5,c=5;
try
{
y=a/(b+c);
System.out.println(y);
}
finally
{
System.out.println("This is finally block");
}
}
}
Output:
1
This is finally block

8
Example -2: When an exception occur but not handled by the catch block

public class FinallyDemo {


public static void main(String[] args) {
int x,y;
int a=10,b=5,c=5;
try
{
y=a/(b-c);
System.out.println(y);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("This is finally block");
}
}
}
Output:
This is finally block
Exception in thread "main" java.lang.ArithmeticException: / by zero
at FinallyDemo.main(FinallyDemo.java:9)

Example -3: When an exception occurs and is handled by the catch block

public class FinallyDemo {


public static void main(String[] args) {
int x,y;
int a=10,b=5,c=5;
try
{
y=a/(b-c);
System.out.println(y);
}
catch(ArithmeticException e)
{
System.out.println("Divided by zero error");
}
finally
{
System.out.println("This is finally block");
}
}
}
Output:
Divided by zero error
This is finally block
9
Java throw keyword:
 The throw keyword in Java is used to implicitly or explicitly throw an exception from a
method or any block of code
 We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly
used to throw a custom exception.
Syntax
throw new exception_class("error message");
Example-1:
import java.lang.*;
class ThrowExcep
{
public static void main (String[] args) {
try
{
throw new ArithmeticException("My Own Exception");
//System.out.println("This is try block");
}
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
}
}
}
Output:
My Own Exception

Example-2:
class ThrowExcep
{
static void fun()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Exception Caught inside fun().");
throw e; // rethrowing the exception
}
}
10
public static void main(String args[])
{
try
{
fun();
}
catch(NullPointerException e)
{
System.out.println("Exception Caught in main().");
}
}
}
Output:
Exception Caught inside fun().
Exception Caught in main().

User-defined Custom Exception:


 Java provides us facility to create our own exceptions which are basically derived classes
of Exception class.
For example MyException in below code extends the Exception class.

Example:
class MyException extends Exception{
public MyException(String s){
// Call constructor of parent Exception
super(s);
}
}
public class ThrowExcep{
public static void main(String args[]){
try
{
throw new MyException("User defined exception");
}
catch (MyException ex)
{
System.out.println("Exception Caught");
System.out.println(ex.getMessage());
}
}
}
Output:
Caught
User defined exception
11
Java throws:
 throws is a keyword in Java that is used in the declaration of a method to indicate that this
method might throw one of the listed type exceptions.
 The caller to these methods has to handle the exception using a try-catch block.
Syntax

type method_name(parameters) throws exception_list

Example-1:

class ThrowsDemo {
public static void main(String[] args)
{
Thread.sleep(10000);
System.out.println("Java Programming");
}
}

Output:
ThrowsDemo.java:4: error: unreported exception InterruptedException; must be caught or
declared to be thrown
Thread.sleep(10000);

Example – 2:

class ThrowsDemo {
public static void main(String[] args) throws InterruptedException
{
Thread.sleep(10000);
System.out.println("Java Programming");
}
}

Output:
Java Programming

12
Example – 3:
class ThrowsDemo {
static void fun() throws ArithmeticException
{
System.out.println("Inside fun().");
throw new ArithmeticException("My Own Exception");
}
public static void main(String[] args)
{
ThrowsDemo obj = new ThrowsDemo();
try
{
fun();
}
catch(ArithmeticException e)
{
System.out.println("caught in main.");
}
}
}
Output:
Inside fun().
caught in main.
Example – 4:
class ThrowsDemo {
static void calculate() throws ArithmeticException
{
System.out.println("Inside Calculate Method");
System.out.println(10/0);
}
public static void main(String args[])
{
try
{
calculate();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:

Inside Calculate Method


java.lang.ArithmeticException: / by zero

13
Throw vs Throws:
S. No. Throw Throws

1 It is used to throw an exception explicitly It is used to declare an exception

2 void m() void m() throws ArithmeticException


{ {
throw new ArithmeticException(“Hai”);
} }
3 Checked exceptions can’t propagated Checked exceptions can be propagated

4 throw is followed by instance throws is followed by exception class

5 throw is used within a method throws is used with method signature

6 We can’t throw multiple exceptions We can declare multiple exceptions

14
15

You might also like