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

Week 13 (Exception Handling)

The document provides an overview of exception handling in Java, detailing what exceptions are, their types (checked and unchecked), and the differences between exceptions and errors. It explains the mechanisms for handling exceptions, including try-catch blocks, the throw and throws keywords, and the use of finally blocks. Additionally, it covers common scenarios where exceptions may occur and the creation of user-defined exceptions.

Uploaded by

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

Week 13 (Exception Handling)

The document provides an overview of exception handling in Java, detailing what exceptions are, their types (checked and unchecked), and the differences between exceptions and errors. It explains the mechanisms for handling exceptions, including try-catch blocks, the throw and throws keywords, and the use of finally blocks. Additionally, it covers common scenarios where exceptions may occur and the creation of user-defined exceptions.

Uploaded by

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

Exception Handling

in Object-Oriented
Programming (Java)

Instructor Name: Khawaja Ammad Badar


Computing and Technology Department, IQRA University Islamabad – H9 Campus - Pakistan
Contents
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
 Terms used in Exception Handling
 Common Scenarios where Exceptions may Occur
 User defined Exceptions
What is an Exception?
3

• An exception in Java is an event that occurs during


the execution of a program and disrupts the normal
flow of instructions. It is a mechanism used to
handle runtime errors, allowing the program to
continue running or terminate gracefully instead of
crashing unexpectedly.
• 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.
Types of Exceptions
4

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 checked at compile time.
• Known to the compiler at runtime, also called runtime Exceptions.
• Examples: ArithmeticException, ArrayIndexOutOfBoundException, etc.
Checked Exception (Example)
5

import java.io.*;
/*The method close() closes the file input stream *
class Example {
It throws IOException*/
public static void main(String args[]) {
FileInputStream fis = null;
fis.close();
/*This constructor FileInputStream(File filename) }
throws FileNotFoundException which is a checked exception */ }

fis = new FileInputStream("B:/myfile.txt");


int k;

/* Method read() of FileInputStream class


also throws a checked exception: IOException */ Output:
Exception in thread "main" java.lang.Error: Unresolved
while(( k = fis.read() ) != -1) { compilation problems: Unhandled exception type
FileNotFoundException Unhandled exception type IOException
System.out.print((char)k);
Unhandled exception type IOException
}
Unchecked Exception (Example)
6

// 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 at
// Attempting to divide by zero 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?
7

• 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)
8

public class ErrorEg {


// Java program illustrating stack overflow error public static void main(String[] args){
// by doing infinite recursion
class StackOverflow { // eg of StackOverflowError
public static void test(int i) { StackOverflow.test(5);
// No correct as base condition leads to }
// non-stop recursion. }
if (i == 0)
return;
else{ Output:
test(i++); Exception in thread "main" java.lang.StackOverflowError
} at StackOverflow.test(ErrorEg.java:7)
} 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
9

Aspect Error Exception


Represents serious problems Represents conditions the program
Definition
beyond recovery. can recover from.
Subclass of Throwable, under
Hierarchy Subclass of Throwable, under Error.
Exception.
OutOfMemoryError,
Examples IOException, ArithmeticException.
StackOverflowError.
Always unchecked (not checked at
Checked/Unchecked Can be checked or unchecked.
compile time).
Typically caused by the environment Typically caused by application or
Cause
or JVM (e.g., hardware failure). code issues.
Cannot be recovered; program Can often be recovered using
Recovery Possibility
typically terminates. exception handling mechanisms.
Should not be handled in code; Can be handled using try-catch
Handling
requires fixing the root cause. blocks or throws keyword.
Error vs Exception and their Class Hierarchy
10

• 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?
11

• 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?
12

• 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.
Terms used in Exception Handling
13

• 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.

• 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.
Exception Handling (try-catch)
14

class ExceptionThrown {
// It throws the Exception(ArithmeticException).
//main method
// Appropriate Exception handler is not found within this method.
public static void main(String args[]){
static int divideByZero (int a, int b){ int a = 1;
// this statement will cause ArithmeticException(/ by zero) int b = 0;
int i = a/b;
return i; try {
} int i = computeDivision(a,b);
// The runTime System searches the appropriate Exception handler }
// in this method also but couldn't have found. So looking forward // matching ArithmeticException
// on the call stack. catch (ArithmeticException ex) {
static int computeDivision (int a, int b) { // getMessage will print description of exception(here / by zero)
int res =0; System.out.println(“Message String=“ +ex.getMessage());
try {
res = divideByZero (a,b);
}
} }
// doesn't matches with ArithmeticException
catch (NumberFormatException ex) { }
System.out.println ("NumberFormatException is occured");
} This method is used to get the detail
return res; Output: message of exception as a string value.
} Message String=/ by zero.
Multiple Catch block
15

public class Main {


public static void main(String[] args) {
try {
int[] array = new int[5];
array[10] = 30 / 0; // May throw ArithmeticException or ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception occurred: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Out of Bounds Exception occurred: " + e.getMessage());
} catch (Exception e) {
System.out.println("General Exception occurred: " + e.getMessage());
}

System.out.println("Rest of the program executes...");


}
}
Throw Keyword
16

• 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)
17

// Java program that demonstrates the use of throw


//main method
class ThrowExcep {
static void fun() { public static void main(String args[]) {
try{ try{
throw new NullPointerException("demo"); fun();
} }
catch (NullPointerException e) { catch(NullPointerException e) {
System.out.println("Caught inside fun()."); System.out.println("Caught in main.");
throw e; Output:
}
// re-throwing the exception Caught inside fun(). }
} Caught in main. }
}
• 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
18

Preceding step

try block

throw
statement

unmatched catch

matching catch

unmatched catch

next step
Throws Keyword
19

• 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.

Scenario:
In any program, 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)
20

//Java program to illustrate error in case


// of unhandled exception
class Test{
public static void main(String[] args) { Solution of Unhandled Example
Thread.sleep(10000); class Test{
System.out.println("Hello"); public static void main(String[] args) throws InterruptedException{
} Thread.sleep(10000);
} System.out.println("Hello");
Output: }
error: unreported exception }
InterruptedException; must be caught or
declared to be thrown

Explanation : In this program, we are getting


compile time error because there is a chance of Explanation : In the above program, by using throws keyword
we handled the InterruptedException and we will get the
exception if the main thread is going to sleep,
output as Hello
other threads get the chance to execute main()
method which will cause InterruptedException.
Throws Keyword (Using try-catch)
21

// 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[]) { Output:
try{ Inside fun().
fun(); caught in main.
}
catch(IllegalAccessException e) {
System.out.println("caught in main.");
}
}
}
Finally Block
22

• 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)
23

// Java program to illustrate finally in // Case where


exceptions do not // occur in the program
class B {
i n the program
public static void main(String[] args) { do no t occur
ns
int k = 55; Exceptio
try {
System.out.println("In try block");
int z = k / 55;
} Output:
catch (ArithmeticException e) {
System.out.println("In catch block"); In try block
Executes whether exception occurs or not
System.out.println("Dividing by zero but caught");
}
finally {
System.out.println("Executes whether exception
occurs or not");
}
}
}
Finally Block (Example-2)
24

// Java program to illustrate finally // Case where exceptions occur // and match in the program
class C {
e spo nding
public static void main(String[] args) { d corr
rs a n
int k = 66; tio n occu es
Exce p match
try { o c k
ca tch bl
System.out.println("In try block");
int z = k / 0;
// Carefully see flow dosen't come here Output:
System.out.println("Flow dosen't came here");
} In try block
catch (ArithmeticException e) { In catch block
System.out.println("In catch block"); Dividing by zero but caught
Finally block, Executes whether an exception occurs or not
System.out.println("Dividing by zero but caught");
}
finally {
System.out.println(“Finally block, Executes whether an exception occurs or not");
}
}
}
Common Scenarios where Exceptions may Occur
25

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
26

• 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{ }
Finally Block (Example-2)
27

/* This is my Exception class, I have named it MyException * you class Main{


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

THANK YOU

You might also like