0% found this document useful (0 votes)
22 views35 pages

Exception Handling

Uploaded by

adeebaa480
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
22 views35 pages

Exception Handling

Uploaded by

adeebaa480
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 35

Exception

Handling in JAVA
Outline
2

◻ What is an Exception
◻ Types of Exceptions
◻ What is an Error
◻ Error vs Exception
◻ What is an Exception Handling
◻ Why we use Exception Handling
What is an Exception?
3

• Dictionary Meaning: Exception is an abnormal condition.

• An exception is an event that alters the normal flow of the program. It is


an object which is thrown at runtime.

• Exceptions are recoverable using try, catch, throw, and throws keywords.

• Derive from class Exception, said to be “thrown” and an Exception


handler “catches” it. For instance, ClassNotFoundException, IOException,
SQLException, etc.
What is Exception?
4
Types of Exceptions
5

Exceptions are divided into two categories:

• Checked Exceptions
• Known to compiler at compile time.
• Must be either handled or specified using throws keyword.
• Examples: IOException, FileNotFoundException, etc.

• Unchecked Exceptions
• Not chekced at compile time.
• Known to the compiler at runtime, also called runtime Exceptions.
• Examples: ArithmeticException, ArrayIndexOutOfBoundException,
etc.
Checked Exception (Example)
6

import java.io.*; while(( k = fis.read() ) != -1)


class Example {
{ System.out.print((char)k);
public static void main(String args[]) }
{ /*The method close() closes
FileInputStream fis = null; the file input stream * It
/*This constructor FileInputStream(File filename) throws IOException*/
throws FileNotFoundException which is a
checked exception */ fis.close();
fis = new FileInputStream("B:/myfile.txt"); }
int k; }
Output:
/* Method read() of FileInputStream class Exception in thread "main" java.lang.Error: Unresolved compilation
problems: Unhandled exception type FileNotFoundException
also throws a checked exception: IOException */ Unhandled exception type IOException
Unhandled exception type IOException
Unchecked Exception (Example)
7

// Java program illustrating exception thrown


// by AritmeticExcpetion class

public class ExceptionEg


{
public static void main(String[] args)
{ Output:
int a = 5, b = 0;
java.lang.ArithmeticException: / by zero
// Attempting to divide by zero at ExceptionEg.main(ExceptionEg.java:8)
try {
int c = a / b;
}
catch (ArithmeticException e)
{
e.printStackTrace();
} This method prints a stack trace for this Throwable
} object on the standard error output stream.
}
What is an Error?
8

• An Error “indicates serious problems that a reasonable application


should not try to catch.”

• Errors are the conditions which cannot get recovered by any handling
techniques.

• Errors belong to unchecked type and mostly occur at runtime.

• Examples: Out of memory error, a System crash error, hardware error,


StackOverflowError etc.
Error (Example)
9

// Java program illustrating stack overflow error


public class ErrorEg
// by doing infinite recursion
{
class StackOverflow
public static void main(String[] args)
{
{
public static void test(int i)
{
// eg of StackOverflowError
// No correct as base condition leads to
StackOverflow.test(5);
// non-stop recursion.
}
if (i == 0)
}
return;
else Output:
{ Exception in thread "main" java.lang.StackOverflowError
at StackOverflow.test(ErrorEg.java:7)
test(i++); at StackOverflow.test(ErrorEg.java:7)
} at StackOverflow.test(ErrorEg.java:7)
} at StackOverflow.test(ErrorEg.java:7)
} at StackOverflow.test(ErrorEg.java:7)
...
Error vs Exception
10

Error Exception

1. An error represents a condition 1. An error which reasonable


serious enough that most applications should catch.
reasonable applications should 2. Array index out of bounds
not try to catch. 3. Arithmetic errors (divide by
2. Virtual Machine Error zero
3. Out of memory 4. Null Pointer Exception
4. Stack overflow 5. I/O Exceptions
5. Thread Death
6. Linkage Error
Error vs Exception and their Class Hierarchy
11

• java.lang.Object
All Java errors implement the java.lang.Throwable, or
• java.lang.Throwable
are extended from another inherited class therein. The
• java.lang.Exception
full hierarchy of error is:
• java.lang.RuntimeException
• java.lang.Object
• java.lang.ArithematicException
• java.lang.Throwable
• java.lang.NullPointerException
• java.lang.Error
• java.lang.VirtualMachineError
• java.lang.AssertionError

The Java Virtual Machine is broken or has run out


of resources necessary for it to continue operating.
•java.lang.Object
• java.lang.Throwable
• java.lang.Exception
• java.io.IOException The AssertionError in Java is thrown when an assert
statement fails (i.e. the result is false).
What is an Exception Handling?
12

• Exception handling is a framework that is used to handle runtime


errors only, compile time errors are not handled by exception
handling in java.

• Exception handling is one of the most important feature of java


programming that allows us to handle the runtime errors caused
by exceptions.
Why we use Exception Handling?
13

To maintain the normal flow of the application.

An exception normally disrupts the normal flow of the


application that is why we use exception handling.

How we can handle the Exceptions?


Recap
14

• What

An exception is an event that alters the normal flow of the program.


Checked (compile time) and unchecked (runtime) exceptions.
An Error indicates serious problems, unchecked type, mostly occur at runtime
Exception handling is a framework that is used to handle runtime errors.

• Why

To maintain the normal flow of the application/program.


Terms used in Exception Handling
15

• Try-Catch: Piece of code of your program that you want to


monitor for exceptions are contained within a try block. If an
exception occurs within the try block, it is thrown. Catch block
can catch this exception and handle it in some logical manner.

• Finally: Any code that absolutely must be executed before a


method returns, is put in a finally block.

• Throw: System-generated exceptions are automatically thrown


by the Java run-time system. Now if we want to manually throw
an exception, we have to use the throw keyword.
Terms used in Exception Handling
16

• Throws: If a method is capable of causing an exception that it does not handle,


it must specify this behavior so that callers of the method can guard themselves
against that exception.

You do this by including a throws clause in the method’s declaration. Basically it is


used for IO Exception. A throws clause lists the types of exceptions that a method
might throw.

This is necessary for all exceptions, except those of type Error or Runtime
Exception, or any of their subclasses. All other exceptions that a method can throw
must be declared in the throws clause. If they are not , a compile-time error will
result.
Exception Handling (try-catch example slide-1)
17

class ExceptionThrown
// The runTime System searches the appropriate Exception
{ handler
// in this method also but couldn't have found. So looking
// It throws the
Exception(ArithmeticException). forward
// Appropriate Exception handler is not found // on the call stack.
within this method. static int computeDivision (int a, int b)
{
static int divideByZero (int a, int b) int res =0;
{ try
{
// this statement will cause res = divideByZero (a,b);
ArithmeticException(/ by zero) }
int i = a/b; // doesn't matches with ArithmeticException
return i; catch (NumberFormatException ex)
} {
System.out.println ("NumberFormatException is
occured");
}
return res;
}
Exception handling (try-catch example slide-2)
18

//main method
public static void main(String args[])
{
int a = 1;
int b = 0;

try
{
int i = computeDivision(a,b);
Output:
}
// matching ArithmeticException Message String=/ by
catch (ArithmeticException ex) zero.
{
// getMessage will print description of exception(here / by zero)
System.out.println(“Message String=“ +ex.getMessage());
}
}

This method is used to get the detail message of exception as a string


} value.
Multi-Catch Block
19

public class TestMultipleCatchBlock


{ public static void main(String args[])
{
try At a time only one
Exception is occurred
{ and at a time only one
int a[]=new int[5]; catch block is
a[5]=30/0; executed.
}
catch (ArithmeticException e) All catch blocks must be
{System.out.println("task1 is ordered from most
specific to most general
completed");} i.e. catch for
catch (ArrayIndexOutOfBoundsException e) ArithmeticException must
{System.out.println("task 2 completed");} come before catch for
catch (Exception e) Exception .
{System.out.println("common task completed");}
System.out.println("rest of the code...");
}
Throw Keyword
20

• throw keyword is used to explicitly throw an exception from a


method or any block of code.

• throw either checked and unchecked exceptions.

• throw keyword is mainly used to throw custom exceptions.

Syntax

throw Instance
Example:
throw new ArithmeticException("/ by zero");
Throw Keyword (Example)
21

//main method
// Java program that demonstrates the use of throw
class ThrowExcep public static void main(String args[])
{ {
try
static void fun()
{
{ fun();
try }
{ catch(NullPointerException e)
throw new NullPointerException("demo"); {
} System.out.println("Caught in main.");
catch (NullPointerException e) }
}
{
System.out.println("Caught inside fun().");
throw e; }
// re-throwing the exception
}
} Output:
Caught inside fun().
Caught in main.
Throw Keyword (Example Explanation)
22

• The flow of execution of the program stops immediately after the throw
statement is executed and the nearest enclosing try block is checked to see if
it has a catch statement that matches the type of exception.

• If it finds a match, controlled is transferred to that statement otherwise next


enclosing try block is checked and so on.

• If no matching catch is found then the default exception handler will halt the
program.
Sequence of Events for throw

Preceding step

try block

throw
statement

unmatched catch

matching catch

unmatched catch

next step
Throws Keyword
24

• throws keyword is used in the signature of 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

exception_list is a comma separated list of all the exceptions which a


method might throw.
Throws Keyword
25

Scenario:
In anyprogram, if there is a chance of rising an exception then compiler always warn
us about it and compulsorily we should handle that checked exception, Otherwise
we will get compile time error saying unreported exception XXX must be caught
or declared to be thrown. To prevent this compile time error we can handle the
exception in two ways:

1.By using throws keyword


2.By using try catch
Unhandled Exception (Example)
26

//Java program to illustrate error in case


// of unhandled exception
class tst Output:
error: unreported exception InterruptedException; must
{ be caught or declared to be thrown
public static void main(String[] args)
{
Thread.sleep(10000);
System.out.println("Hello");
} Explanation : In this program, we are getting compile time error because there
is a chance of exception if the main thread is going to sleep, other threads get
} the chance to execute main() method which will cause InterruptedException.
Use of throws Keyword (Example)
27

// Java program to illustrate throws


class tst
{
public static void main(String[] args) throws InterruptedException
{
Thread.sleep(10000);
System.out.println(“Dear Students");
}
}
Explanation : In the above program, by using throws keyword we handled the
Output: InterruptedException and we will get the output as Dear Students
Dear Students
Throws Keyword (Using try-catch)
28

// Java program to demonstrate working of throws


class ThrowsExecp
{
static void fun() throws IllegalAccessException
{
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try
Ouput:
{
Inside fun().
fun(); caught in main.
}
catch(IllegalAccessException e)
{
System.out.println("caught in main.");
}
}
}
Finally Block
29

• The finally keyword is used in association with a try-catch block


and guarantees that a section of code will be executed, even if
an exception is thrown.

• The finally block will be executed after the try and catch blocks,
but before control transfers back to its origin.

• finally block will execute whether an exception occurs or not or


whether corresponding catch block found or not.
Finally Block (Example-1)
30
// Java program to illustrate finally in // Case where exceptions do not // occur in the
program
class B am
{ r i n t he progr
u
s do not occ
public static void main(String[] args) i on
Except
{
int k = 55;
try
{
System.out.println("In try block");
int z = k / 55; Output:
}
In try block
catch (ArithmeticException e) Executes whether exception occurs or not
{
System.out.println("In catch block");
System.out.println("Dividing by zero but caught");
}
finally
{
System.out.println("Executes whether exception occurs or not");
}
}
Finally Block (Example-2)
31
// Java program to illustrate finally // Case where exceptions occur // and match in the
program
g
class C
r e s pondin
r
{
r s a nd co
u
public static void main(String[] args)
p ti on occ tches
{ Exce lock ma
b
int k = 66; cat c h
try {
System.out.println("In try block");
int z = k / 0;
// Carefully see flow dosen't come here
System.out.println("Flow dosen't came here");
Output:
}

catch (ArithmeticException e) { In try block


System.out.println("In catch block"); In catch block
System.out.println("Dividing by zero but caught"); Dividing by zero but caught
} Finally block, Executes whether an exception occurs
or not
finally
{
System.out.println(“Finally block, Executes whether an exception occurs or not");
}
}
}
Common Scenarios where Exceptions may Occur

ArithmeticException occurs
int a=50/0; //ArithmeticException

NullPointerException occurs
String s=null;
System.out.println(s.length()); //NullPointerException

NumberFormatException occurs
String s="abc";
int i=Integer.parseInt(s); //NumberFormatException

ArrayIndexOutOfBoundsException occurs
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
User-defined Exceptions
If we can create your own exceptions in Java. Then, keep the following points in mind when
writing your own exception classes.

• All exceptions must be a child of Throwable.

• If you want to write a checked exception that is automatically enforced by the Handle or
Declare Rule, you need to extend the Exception class.

• If you want to write a runtime exception, you need to extend the RuntimeException
class.

• For example, we can define our own Exception class as below: class MyException
extends Exception{ }
User-defined Exception (Example)
/* This is my Exception class, I have named it class Example1
MyException * you can give any name, just {
public static void main(String args[])
remember that it should * extend Exception class */
{
try
class MyException extends Exception { System.out.println("Starting of try block");
{ // I'm throwing the custom exception using throw
String str1; throw new MyException("This is My error Message");
/* Constructor of custom exception class * here I am }
copying the message that we are passing while * catch(MyException exp)
{
throwing the exception to a string and then
System.out.println("Catch Block") ; System.out.println(exp) ;
displaying * that string along with the message. */ }
}
MyException(String str2) }
{ str1=str2; }
public String toString()
{ return ("MyException Occurred: "+str1) ; }
} Output:
Starting of try block
Catch Block
MyException Occurred: This is My
error Message
35

Thanks

You might also like