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

SE101 Lec6 ExceptionHandling

Uploaded by

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

SE101 Lec6 ExceptionHandling

Uploaded by

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

Lecture 6

Exception Handling
Exception:

 An exception is an event, which occurs during the execution of


a program, that disrupts the normal flow of the program's
instructions.

 The Java uses exceptions to handle errors and other


exceptional events.
Throwing an Exception:
 When an error occurs within a method, the method creates
an object (exception object) and hands it off to the runtime
system.

 exception object, contains information about the error,


including its type and the state of the program when the
error occurred.

 Creating an exception object and handing it to the runtime


system is called throwing an exception.
 The runtime system searches the call stack for a method that
contains a block of code that can handle the exception.

 This block of code is called an exception handler.

 The exception handler chosen is said to catch the exception.


Hierarchy of Java Exception classes
 The java.lang.Throwable class is the root class of Java Exception hierarchy
which is inherited by two subclasses: Exception and Error.
Types of Java Exceptions

There are mainly two types of exceptions: checked


and unchecked. Here, an error is considered as the
unchecked exception.

According to Oracle, there are three types of


exceptions:

1.Checked Exception
2.Unchecked Exception
3.Error
Difference between Checked and Unchecked
Exceptions

1) Checked Exception

The classes which directly inherit Throwable class except RuntimeException and
Error are known as checked exceptions e.g. IOException, SQLException etc.
Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes which inherit RuntimeException are known as unchecked exceptions


e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
etc. Unchecked exceptions are not checked at compile-time, but they are
checked at runtime.

3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError


etc.
Common Scenarios of Java Exceptions
There are given some scenarios where unchecked exceptions may occur. They
are as follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the variable
throws a NullPointerException.

String s=null;
System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs

The wrong formatting of any value may occur NumberFormatException.


Suppose I have a string variable that has characters, converting this variable
into digit will occur NumberFormatException.

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

4) A scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:

int a[]=new int[5];


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

 This means that code that might throw certain exceptions must be enclosed
by either of the following:

1. A try statement that catches the exception.

2. A method that specifies that it can throw the exception.


(The method must provide a throws clause that lists the exception.)
Catching Exception:
 A method catches an exception using a combination of the try and catch
keywords.

 A try/catch block is placed around the code that might generate an exception.

 Code within a try/catch block is referred to as protected code

try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}
Multiple Catch Blocks:
A try block can be followed by multiple catch blocks.

try{
// protected code
}
catch (ExceptionName1 e1){
}
e1
catch (ExceptionName2 e2){
}
e2
catch (ExceptionName3 e3){
} e3
finally clause:

finally {
// this block always executes
}

 The finally keyword is used to create a block of code that follows a try
block.

 A finally block of code always executes, whether or not an exception has


occurred.
Throws/throw:
public void doAddition() throws MyException {

throw new MyException();


}

 If a method does not handle a checked exception, the method must


declare it using the throws keyword.

 The throws keyword appears at the end of a method's signature.

 You can throw an exception by using the throw keyword.


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);
}
}
}
Declaring your own Exception Class:
You can create your own exceptions in Java.

Note:

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

Public class MyException extends Exception {


}
// File Name InsufficientFundsException.java
import java.io.*;

public class InsufficientFundsException extends Exception


{
private double amount;
public InsufficientFundsException(double amount)
{
this.amount = amount;
}
public double getAmount()
{
return amount;
}
}
// File Name CheckingAccount.java
import java.io.*;

public class CheckingAccount


{
private double balance;
private int number;
public CheckingAccount(int number)
{
this.number = number;
}
public void deposit(double amount)
{
balance += amount;
}
public void withdraw(double amount) throws InsufficientFundsException
{
if(amount <= balance)
{
balance -= amount;
}
else
{
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}
public double getBalance()
{
return balance;
}
public int getNumber()
{
return number;
}
}
// File Name BankDemo.java
public class BankDemo
{
public static void main(String [] args)
{
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);
try
{
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
}catch(InsufficientFundsException e)
{
System.out.println("Sorry, but you are short $"
+ e.getAmount());
e.printStackTrace();
}
}
}
Examples
public class ExceptionTest{

public static void main(String args[]){

int a[] = new int[2];

try{
System.out.println("Accessing element three :" + a[3]);
} catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
finally{
a[0] = 6;
System.out.println("First element value: " +a[0]);
System.out.println("The finally statement is executed");
}

}
}
Answer:

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3


First element value: 6
The finally statement is executed
Question: Is the following code legal?

try {

} finally {

}
Question: What exception types can be caught by
the following handler?

catch (Exception e) {

}
Question: Is there anything wrong with this exception
handler as written? Will this code compile?

try {

} catch (Exception e) {

} catch (ArithmeticException a) {

}
Question: Match each situation in the first list with an item in the second list.

a.
int[] A;
A[0] = 0;

b.
The JVM starts running your program, but the JVM can't find the Java platform
classes. (The Java platform classes reside in classes.zip or rt.jar.)

c.
A program is reading a stream and reaches the end of stream marker.

d.
Before closing the stream and after reaching the end of stream marker, a program
tries to read the stream again.

__error
__checked exception
__compile error
__no exception
Thank You

You might also like