0% found this document useful (0 votes)
11 views52 pages

Chapter 5 Exception Handling

Assembly Level /Machine Organization 3

Uploaded by

yohannestagel5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views52 pages

Chapter 5 Exception Handling

Assembly Level /Machine Organization 3

Uploaded by

yohannestagel5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Chapter Five

Exception Handling
Contents

• Exception

• Types of Exception

• Built - in Exceptions

• Catching Exceptions

• The Throws/ Throw Keywords

• User - defined Exceptions


Exception
• An exception (or exceptional event) is a problem that arises during the

execution of a program.
• When a Java program performs an illegal operation (division by zero, access

an array at a position which does not exist, etc) an event known as exception

happens.
• When an exception occurs, we say an exception is thrown.

Example
 ArithmeticException,

 ArrayIndexOutOfBoundsException,

 NumberFormatException

 IOException, FileNotFoundException, etc


Cont…
• Usually, when an exception occurs, the program will
terminate immediately.

• However, Java provides ways to detect that an exception has


occurred.

• This process is called exception handling.

• When an exception occurs the normal flow of the program is


disrupted and the program/application terminates abnormally,
which is not recommended, therefore, these exceptions are to
be handled .
Cont…
• An exception can occur for many different reasons. Following are
some scenarios where an exception occurs.
 A user has entered an invalid data.
 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of
communications or the JVM has run out of memory.

• Some of these exceptions are caused by


 user error,

 others by programmer error, and

 others by physical resources that have failed in some manner.

• Based on these, we have three categories of Exceptions.


Checked exceptions

• A checked exception is an exception that occurs at the

compile time,

• these are also called as compile time exceptions.

• These exceptions cannot simply be ignored at the time of


compilation, the programmer should take care of (handle) these
exceptions.

• For example, if you use FileReader class in your program to read

data from a file, if the file specified in its constructor doesn't


exist, then a FileNotFoundException occurs, and the compiler
prompts the programmer to handle the exception.
Cont…
Example
import java.io.File;
import java.io.FileReader;

public class FileClass{


public static void main(String args[]){

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

FileReader fr = new FileReader(file);


}}

If you try to compile the above program, you will get the following exceptions.
C:\>javac File.java
FilenotFound_Class.java:8: error: unreported exception
FileNotFoundException;
must be caught or declared to be thrown
FileReader fr = new FileReader(file);
^1 error
Cont…
• Note: Since the methods read() and close() of FileReader class throws
IOException, you can observe that the compiler notifies to handle
IOException, along with FileNotFoundException.
Unchecked exceptions
• An unchecked exception is an exception that occurs at the time of

execution.

• These are also called as Runtime Exceptions.

• These include programming bugs, such as logic errors or

improper use of an API.

• Runtime exceptions are ignored at the time of compilation.


Cont…
• For example, if you have declared an array of size 5 in your program, and trying
to call the 6th element of the array then an
ArrayIndexOutOfBoundsException exception occurs.
public class UncheckedClass {
public static void main(String args[]){
int num[]={1,2,3,4};
System.out.println(num[5]);
}}

• If you compile and execute the above program, you will get the following

exception.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at

Exceptions.UncheckedClass.main(UncheckedClass.java:8)
Errors

• These are not exceptions at all, but problems that


arise beyond the control of the user or the
programmer.
• Errors are typically ignored in your code because
you can rarely do anything about an error.
• For example, if a stack overflow occurs, an error will
arise.
• They are also ignored at the time of compilation.
Exception Hierarchy

• All exception classes are subtypes of the java.lang.Exception class.


• The exception class is a subclass of the Throwable class.
• Other than the exception class there is another subclass called Error which is

derived from the Throwable class.


• Errors are abnormal conditions that happen in case of severe failures,

these are not handled by the Java programs.


• Errors are generated to indicate errors generated by the runtime environment.

Example: JVM is out of memory.


• Normally, programs cannot recover from errors.
• The Exception class has two main subclasses: IOException class and

RuntimeException Class
Cont…
Built - in Exceptions

• Java defines several exception classes inside the standard


package java.lang.
• The most general of these exceptions are subclasses of
the standard type RuntimeException.
• Since java.lang is implicitly imported into all Java
programs, most exceptions derived from
RuntimeException are automatically available.
• Java defines several other types of exceptions that
relate to its various class libraries.
Cont…
• Following is the list of Java Unchecked RuntimeException
Cont…
Cont…
• Following is the list of Java Checked Exceptions Defined in
java.lang
Exceptions Methods

• Following is the list of important methods available in the


Throwable class
Catching Exceptions

• 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.
• try block: Method calls which may cause an exception can/must be put in a try block.
• catch block: the catch block indicates what should happen in case an exception
occurred.
Remarks:
 Variables defined in the try block are only local.

 Define and initialize the variables outside the try block.

 If you want that the program terminates, use System.exit(-1) in the catch block.

 The nonzero value -1 indicates that the program terminates abnormally.

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


Cont…
• the syntax for using try/catch looks like the following:

try{
//Protected code
}catch(ExceptionName e1){

//Catch block }

• The code which is prone to exceptions is placed in the try block.


• When an exception occurs, that exception occurred is handled by catch

block associated with it.


• Every try block should be immediately followed either by a catch block or

finally block.
Cont…
• A catch statement involves declaring the type of exception you are trying to
catch.
• If an exception occurs in protected code, the catch block (or blocks)
that follows the try is checked.
• If the type of exception that occurred is listed in a catch block, the exception
is passed to the catch block much as an argument is passed into a method
parameter.
• When an exception occurs, Java creates an exception object which (is called
e1 in the above syntax) contains information about the error.
• Every exception object contains a string message, which can be used rather
then printing your own message.
Cont…
Example
// File Name : ExceptionClass.java
import java.io.*;
public class ExceptionClass {
public static void main(String args[]){
try{
int a[] = new int[2];
System.out.println("Access element three :" +
a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");}}

This will produce the following result


Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
Question: In which of the following programs an exception not be Thrown
A C
Class a{ Class C{
void calculate(){ void Read(){
int x; int a;
int y; int b;
Scananner s=new Scanner(System.in);
int z=1; a=s.nextInt();
for (int i=1;i<=x;i++) b=s.nextInt();
z=z*i;}} int z=a+b;}}

B D
Class B{ Class rectangle{
void calculate(){ int x[5]={5,6,9,8,7,9}
File f=new File(“abc.txt”); void show(){
FileReader fr=new For(int i=0;i<=6;i++)
FileReader(); System.out.println(“item “+
Fr.read(f);}} (i+1)+”:”+x[i]);}}
Contents
multiple catch block
Throws/ Throw Keywords
User - defined Exceptions
Multiple Catch Blocks

• A try block can be followed by multiple catch blocks.


• The syntax for multiple catch blocks looks like the following:
try{

//Protected code

}catch(ExceptionType1 e1){

//Catch block1

}catch(ExceptionType2 e2){

//Catch block2

}catch(ExceptionType3 e3){

//Catch block3}
Cont…
• The previous statements demonstrate three catch blocks, but you can

have any number of them after a single try.


• If an exception occurs in the protected code, the exception is thrown to

the first catch block in the list.


• If the data type of the exception thrown matches ExceptionType1, it

gets caught there.


• If not, the exception passes down to the second catch statement.
• This continues until the exception either is caught or falls through

all catches, in which case the current method stops execution and

the exception is thrown down to the previous method on the call stack.
Cont…
• Example
try{
file = new FileInputStream(fileName);
x = (byte) file.read();
}catch(IOException i){
i.printStackTrace();
return -1;
}catch(FileNotFoundException f) //Not valid!{
f.printStackTrace();
return -1;}
Cont…
Catching Multiple Type of Exceptions
• Since Java 7, you can handle more than
one exception using a single catch block,
this feature simplifies the code. Here is how
you would do it:
catch (IOException|FileNotFoundException ex) {
logger.log(ex);
throw ex;
The Throws/ Throw Keywords

• The throw and throws is the concept of


exception handling
• the throw keyword throw the exception
explicitly from a method or a block of code
whereas the throws keyword is used in
signature of the method
Cont…
• If a method does not handle a exception, the method must be

declared with the throws keyword.

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

• You can throw an exception, either a newly instantiated one or an

exception that you just caught, by using the throw keyword.

• throws is used to postpone the handling of a checked exception

• throw is used to invoke an exception explicitly.

• A list of differences between throw and throws are given below:.


Cont…
Basis of throw throws
Differences

Java throw keyword is used throw Java throws keyword is used in the
Definition an exception explicitly in the code, method signature to declare an
inside the function or the block of exception which might be thrown
code. by the function while the execution
of the code.

Syntax The throw keyword is followed by The throws keyword is followed


an instance of Exception to be by class names of Exceptions to be
thrown. thrown.

Declaration throw is used within the method. throws is used with the method
signature.

Internal We are allowed to throw only one We can declare multiple


implementatio exception at a time i.e. we cannot exceptions using throws keyword
n throw multiple exceptions. that can be thrown by the method.
For example, main() throws
IOException, SQLException.
Java throw Example

public class TestThrow {


//defining a method
public static void checkNum(int num) {
if (num < 1) {
throw new ArithmeticException("\
nNumber is negative, cannot calculate square");
}
else {
System.out.println("Square of " + num + " is " + (num*num));
} }
//main method
public static void main(String[] args) {
TestThrow obj = new TestThrow();
obj.checkNum(-3);
System.out.println("Rest of the code.."); } }
Java throws Example

public class TestThrows {


//defining a method
public static int divideNum(int m, int n) throws ArithmeticException {
int div = m / n;
return div;
}
//main method
public static void main(String[] args) {
TestThrows obj = new TestThrows();
try {
System.out.println(obj.divideNum(45, 0));
}
catch (ArithmeticException e){
System.out.println("\nNumber cannot be divided by 0");
}
System.out.println("Rest of the code.."); }
Java throw and throws Example

public class TestThrowAndThrows


{
// defining a user-defined method
// which throws ArithmeticException
static void method() throws ArithmeticException
{
System.out.println("Inside the method()");
throw new ArithmeticException("throwing ArithmeticException");
}
//main method
public static void main(String args[])
{
try
{
method();
}
catch(ArithmeticException e)
{
System.out.println("caught in main() method");
} }}
Cont…
• A method to be declared can handle more than one exception, in
which case the exceptions are declared in a list separated by commas.
• For example, the following method declares that it throws a
RemoteException and an InsufficientFundsException
import java.io.*;
public class className{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException{
// Method implementation}
//Remainder of class definition}
Cont…
• The finally block follows a try block or a catch block.
• A finally block of code always executes, irrespective of

occurrence of an Exception.
• Using a finally block allows you to run any cleanup-

type statements that you want to execute, no matter what


happens in the protected code.
• A finally block appears at the end of the catch blocks and
has the following syntax:
Cont…

public class ExcepTest{


public static void main(String args[]){
int a[] = new int[2];
try{
System.out.println("Access 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");}}}

The above program returns the following


Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
Cont..
Note
A catch clause cannot exist without a try statement.
It is not compulsory to have finally clauses
whenever a try/catch block is present.
The try block cannot be present without either
catch clause or finally clause.
Any code cannot be present in between the try,
catch, finally blocks.
The try - with - resources

• Generally, when we use any resources like


streams, connections, etc. we have to close
them explicitly using finally block.
• In the following program, we are reading
data from a file using FileReader and we are
closing it using finally block
import java.io.*; System.out.println(c);//print each character line by

public class FileREadeEXception { line

public static void main(String[] args) { }

FileReader fr=null; //creat file reader object }catch(IOException e){//catche

try{//code which cause exception exception

File file=new File("file.txt") ;//read and open file e.printStackTrace();}

fr=new FileReader(file);//pass opened file to finally{

FileReader Method try{

char[] a=new char[50];//array to store charater fr.close();

from file.txt }catch(IOException ex){

fr.read(a);//read and store in array a ex.printStackTrace();

for(char c:a){//iteratiel read characters from a } }//end of finaly

using for in loop }//end of main

}//end of class
Cont…

• try-with-resources, also referred as automatic resource


management, is a new exception handling mechanism that was
introduced in Java 7, which automatically closes the resources used
within the try catch block.
• To use this statement, you simply need to declare the required

resources within the parenthesis, and the created resource will be


closed automatically at the end of the block.
• Following is the syntax of try-with-resources statement.

try(FileReader fr=new FileReader("file path")){


//use the resource
}catch(){
//body of catch }}
Cont…
import java.io.FileReader;
import java.io.IOException;
public class TryWithResourceClass {
public static void main(String args[]){
try(FileReader fr=new FileReader(“D://file.txt")){
char [] a = new char[50];
fr.read(a); // reads the contentto the array
for(char c : a)
System.out.print(c); //prints the characters one by one
}catch(IOException e){
e.printStackTrace();}}}
User - defined Exceptions

• Java user-defined exception is a custom exception created and throws that

exception using a keyword ‘throw’.


• It is done by extending a class ‘Exception’.

• An exception is a problem that arises during the execution of the program.

• In Object-Oriented Programming language, Java provides a powerful

mechanism to handle such exceptions.


• Java allows to create own exception class, which provides own exception

class implementation.
• Such exceptions are called user-defined exceptions or custom exceptions.
Cont…
Syntax
 We do not have any particular syntax for Java user-defined exception; we
will see how to create a User-defined exception as follows
class SampleException{
public static void main(String args[]){
try{
throw new UserException(<value>); // used to create new exception and throw
}catch(Exception e){
System.out.println(e);}
}//end of main method
}//end of class SampleException

class UserException extends Exception{ }


Cont…

• while creating an exception class, it needs to


be extended from java. lang.Exception.
• Keyword ‘throw’ is used to create a new
Exception and throw it to catch block.
• Example a user defined exception to catch
Invalid Employee Id
Cont…
import java.util.*; }
class EmployeeException extends Exception }
{ public static void main(String args[])
public EmployeeException(String s) {
{ SampleEmp emp = new SampleEmp();
super(s); Scanner s=new Scanner(System.in);
} System.out.println("Enter an Employee ID");
} emp.empid=s.nextInt();
class SampleEmp try
{ {
int empid; emp.empIDCheck(emp.empid);
void empIDCheck(int EmpID) throws }
EmployeeException{ catch (EmployeeException e)
if(EmpID<=0 || EmpID>999){ {
throw new EmployeeException("Invalid System.out.println("Exception caught");
Employee ID"); System.out.println(e.getMessage());
} }
else{ }
System.out.println(empid+"valid Id }
Number");
Cont…
• When running the above program the
followings are the possible output
When Id number between 0 and 999 When Id number is not between 0 and 999
Enter an Employee ID
Enter an Employee ID 100002
100 Exception caught
100valid Id Number Invalid Employee ID
Exmple2:Check if one number is less than 4
import java.util.*;
class SampleException extends Exception
{
private int e; public static void main(String[] args)
SampleException(int num1) { int a ,b;
{ Scanner s=new Scanner(System.in);
e = num1;} System.out.println("Enter the first number");
public String toString() a=s.nextInt();
{ System.out.println("Enter the second number");
return "(" + e +") is less than Ten"; b=s.nextInt();
}} try
class Demo1 {
{ sum(a,b);
static void sum(int num,int num1) throws }
SampleException catch(SampleException e1)
{ {
if(num1<10){ System.out.println(e1);
throw new SampleException(num1);} }
else{ }
System.out.println("sum="+(num+num1));} }
}
Cont…
• When running the program it will have the following possible
outputs

Option 1 output(if exception not thrown) Option 2 output(if exception thrown)


Enter the first number Enter the first number
20 50
Enter the second number Enter the second number
30 3
sum=50 (3) is less than Ten
Example 3
import java.util.Scanner; System.out.println("Enter only even
class OddNumberException extends number : ");
Exception { num = Integer.parseInt(Sc.nextLine());
OddNumberException() { try {
super("Invalid input:Odd number "); if (num % 2 != 0) throw (new
} OddNumberException());
OddNumberException(String msg) { else System.out.println(num + " is an even
super(msg); number");
} }
} catch(OddNumberException e) {
public class UserdefinedException System.out.println("Error :" +
e.getMessage());
{ public static void main(String[] args){
}
int num;
System.out.println("End of Program");
Scanner Sc = new
Scanner(System.in); }
}
Class work

• Write a java program which read height and width of


a rectangle from the user. The program should have
user defined exception to check whether width and
height are greater than zero. If either height or width
is less then 0 it should return width and height must
be greater than 0 otherwise it return the area of the
rectangle.
Questions
1. What are the two exceptions? Describe their difference.
List down some example of each exception.

2. What is protected code in exception handling?

3. What are the try and catch block in exception handling.

4. List down some built-in exception methods.

5. How errors occur and how to handle it in programming


Cont…
• Write a java program which use a user defined exception called
StudentException. This exception throws an exception if you read students
total mark less than 0 and greater than 100. If you read total mark between 0
and 100 the program should print the mark entered and its equivalent letter
grade based on the following condition.
Mark>=90,grade=A+
Mark>=85,grade=A
Mark>=80,grade=A-
Mark>=75,grade=B+
Mark>=70,grade =B
Mark>=65,grade=B-
Mark>=60,grade =C+
Mark>=50,grade=C
Mark>=45,grade=C-
Mark>=40,grade=D

You might also like