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

Chapter 4 - Exception Handling - Final

Exception handling in java

Uploaded by

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

Chapter 4 - Exception Handling - Final

Exception handling in java

Uploaded by

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

Object Oriented Programming

Instructor: Solomon (Ph.D)


Chapter 4: Exception Handling
Exceptions
• An exception is an unexpected event that occurs during
program execution. It affects the flow of the program
instructions which can cause the program to terminate
abnormally.
• An exception can occur for many reasons. Some of them
are:
– Invalid user input
– Device failure
– Loss of network connection
– Physical limitations (out of disk memory)
– Code errors
– Opening an unavailable file, etc.
Exception hierarchy
• Here is a simplified diagram of the exception hierarchy in
Java.

• The Throwable class is the root class in the hierarchy.


Note that the hierarchy splits into two branches: Error
and Exception.
Exception hierarchy …
• Errors:
– They represent irrecoverable conditions such as JVM running out
of memory, memory leaks, stack overflow errors, library
incompatibility, infinite recursion, etc.
– They are usually beyond the control of the programmer and we
should not try to handle errors.
• Exceptions:
– They can be caught and handled by the program. When an
exception occurs within a method, it creates an object. This object
is called the exception object.
– It contains information about the exception such as the name and
description of the exception, and state of the program when the
exception occurred.
– We will learn how to handle these exceptions.
Exception Types
• The exception hierarchy also has two branches:
RuntimeException and IOException.
(1) RuntimeException:
– A runtime exception happens due to a programming error.
And, it is a good practice to correct them instead of handling
them. They are also known as unchecked exceptions.
– These exceptions are not checked at compile-time but run-
time. Some of the common runtime exceptions are:
▪ Improper use of an API - IllegalArgumentException
▪ Null pointer access (missing the initialization of a variable) -
NullPointerException
▪ Out-of-bounds array access - ArrayIndexOutOfBoundsException
▪ Dividing a number by 0 – ArithmeticException
− You can think about it in this way. “If it is a runtime exception,
it is your fault”.
Exception Types …
(2) IOException:
– An IOException is also known as a checked exception. They
are checked by the compiler at the compile-time, and the
programmer is prompted to handle these exceptions.
– Some of the examples of checked exceptions are:
▪ Trying to open a file that doesn’t exist results in
FileNotFoundException
▪ Trying to read past the end of a file - reading after the end of
file.

• Now we know about exceptions, we will learn about


handling exceptions.
Exception Handling
• We know that exceptions abnormally terminate the
execution of a program. That is why it is important to
handle exceptions.
• Here’s a list of different approaches to handle exceptions
in Java:
– try...catch block
– finally block
– throw and throws keyword
(1) try...catch block
– The try-catch block is used to handle exceptions in Java. Here's
the syntax of try...catch block:
try {
// code
}
catch(Exception e) {
// code
}
Exception Handling …
– The try block includes the code that might generate an exception.
– The catch block includes the code that is executed when there
occurs an exception inside the try block.
class Main {
public static void main(String[] args) {
Output:
try {
ArithmeticException => / by zero
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}

− When the program encounters this code, ArithmeticException


occurs. And, the exception is caught by the catch block and
executes the code inside the catch block.
− The catch block is only executed if there exists an exception inside
the try block.
− Note: In Java, we can use a try block without a catch block.
However, we cannot use a catch block without a try block.
Exception Handling …
(2) try...finally block
− We can also use the try block along with a finally block. In this
case, the finally block is always executed whether there is an
exception inside the try block or not.
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
}
finally {
System.out.println("Finally block is always executed");
}
}
}
Output:
Finally block is always executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:4)

− We can see that the code inside the try block is causing an
exception. However, the code inside the finally block is
executed irrespective of the exception.
Exception Handling …
• try...catch...finally block
− In Java, we can also use the finally block after the try...catch
block. For example,
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

class Main {
public static void main(String[] args) {
Scanner sc = null;
try {
sc = new Scanner(new File("demo.txt"));
while(sc.hasNext() == true)
System.out.println(sc.nextLine());
} catch (FileNotFoundException e) {
System.out.println("File not found");
} finally {
if(sc != null) sc.close();
System.out.println("Program completed");
}
}
}

Output:
hi
hello
Program completed
Exception Handling …
− Since the finally block is always executed, we have
included code to close the Scanner inside the finally
block.
− It is a good practice to use finally block to include
important cleanup code like closing a file or connection.
− Note: There are some cases when a finally block does not
execute:
▪ Use of System.exit() method
▪ An exception occurs in the finally block
▪ The death of a thread
Exception Handling …
• Multiple Catch blocks
− For each try block, there can be zero or more catch blocks.
Multiple catch blocks allow us to handle each exception
differently.
− The argument type of each catch block indicates the type of
exception that can be handled by it. For example,
class ListOfNumbers {
int[] arr = new int[10];
void writeList() {
try {
arr[10] = 11;
}
catch(NumberFormatException e1) {
System.out.println("NumberFormatException => " + e1.getMessage());
}
catch(IndexOutOfBoundsException e2) {
System.out.println("IndexOutOfBoundsException => " + e2.getMessage());
}
}
}
class Main {
public static void main(String[] args) {
ListOfNumbers list = new ListOfNumbers();
list.writeList();
Output:
}
IndexOutOfBoundsException => Index 10 out of bounds for length 10
Exception Handling …
− Here, we are trying to assign a value to the index 10. Hence,
IndexOutOfBoundsException occurs.
− When an exception occurs in the try block,
▪ The exception is thrown to the first catch block. The first catch
block does not handle an IndexOutOfBoundsException, so it
is passed to the next catch block.
▪ The second catch block in the above example is the appropriate
exception handler because it handles an
IndexOutOfBoundsException. Hence, it is executed.
Exception Handling …
• Catching Multiple Exceptions
− Before Java 7, we had to write multiple exception handling codes for
different types of exceptions even if there was code redundancy.
− Example 1: Multiple catch blocks
class Main {
public static void main(String[] args) {
try {
int[] array = new int[10];
array[10] = 30 / 0;
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) { Output:
System.out.println(e.getMessage()); / by zero
}
}
}

− In this example, two exceptions may occur:


▪ ArithmeticException because we are trying to divide a number by 0.
▪ ArrayIndexOutOfBoundsException because we have declared a
new integer array with array bounds 0 to 9 and we are trying to assign a
value to index 10.
Exception Handling …
• Handling Multiple Exceptions in a catch Block
− From Java SE 7 and later, we can now catch more than one type
of exception in a single catch block.
− Each exception type that can be handled by the catch block is
separated using a vertical bar or pipe |.
− Its syntax is:
try {
// code
} catch (ExceptionType1 | Exceptiontype2 ex) {
// catch block
}

− Example 2: Multi-catch block


class Main {
public static void main(String[] args) {
try {
int[] array = new int[10];
array[10] = 30 / 0;
} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
} Output:
} / by zero
}
Exception Handling …
− Catching multiple exceptions in a single catch block reduces
code duplication and increases efficiency.
− The bytecode generated while compiling this program will be
smaller than the program having multiple catch blocks as there
is no code redundancy.
• Catching base Exception
− When catching multiple exceptions in a single catch block, the
rule is generalized to specialized.
▪ This means that if there is a hierarchy of exceptions in the catch
block, we can catch the base exception only instead of catching
multiple specialized exceptions.
Exception Handling …
− Example 3: Catching base exception class only
class Main {
public static void main(String[] args) {
try {
int[] array = new int[10];
array[10] = 30 / 0;
} catch (Exception e) {
Output:
System.out.println(e.getMessage());
}
/ by zero
}
}

− We know that all the exception classes are subclasses of the


Exception class. So, instead of catching multiple specialized
exceptions, we can simply catch the Exception class.
− If the base exception class has already been specified in the
catch block, do not use child exception classes in the same
catch block. Otherwise, we will get a compilation error.
Exception Handling …
− Example 4: Catching base and child exception classes
class Main {
public static void main(String[] args) {
try {
int[] array = new int[10];
array[10] = 30 / 0;
} catch (Exception | ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
}

Output:
Main.java:6: error: Alternatives in a multi-catch statement cannot be related by subclassing
− In this example,
▪ ArithmeticException and ArrayIndexOutOfBoundsException
are both subclasses of the Exception class. So, we get a compilation
error.
Exception Handling …
(3)throw and throws
• throws keyword:
− We use the throws keyword in the method declaration to
declare the type of exceptions that might occur within it.
− Its syntax is:
accessModifier returnType methodName() throws ExceptionType1, ExceptionType2 … {
// code
}

− As you can see from the above syntax, we can use throws to
declare multiple exceptions.
Exception Handling …
− Example 1: throws Keyword
class Sample {
public int division(int a, int b) throws ArithmeticException {
int res = a / b;
return res;
}
}
class Main {
public static void main(String[] args) {
Sample obj = new Sample();
try{
System.out.println(obj.division(15,0));
} catch(ArithmeticException e){
System.out.println(e.getMessage());
}
}
}

Output:
/ by zero
Exception Handling …
• Throwing multiple exceptions
− Here's how we can throw multiple exceptions using the throws
keyword.
import java.io.*;

class Main {
public static void findFile() throws IOException, InvalidClassException {

// code that may produce IOException


… … …
// code that may produce InvalidClassException
… … …
}
public static void main(String[] args) {
try{
findFile();
} catch(IOException e1){
System.out.println(e1.getMessage()); Here, the findFile() method specifies
} catch(InvalidClassException e2){ that it can throw IOException, and
System.out.println(e2.getMessage()); InvalidClassException in its throws
} clause.
}
}
Exception Handling …
import java.io.*;

class Main {
public static void testMethod() throws ArithmeticException,
ArrayIndexOutOfBoundsException {
int[] array = new int[10];
array[10] = 18; // ArrayIndexOutOfBoundsException
array[1] = 30 / 0; // ArithmeticException
}
public static void main(String[] args) {
try {
testMethod();
} catch(ArrayIndexOutOfBoundsException | ArithmeticException ex){
System.out.println(ex.getMessage());
}
}
}
Output:
Index 10 out of bounds for length 10
Exception Handling …
• throw keyword:
− The throw keyword is used to explicitly throw a single exception.
− When an exception is thrown, the flow of program execution
transfers from the try block to the catch block. We use the
throw keyword within a method.
− Its syntax is:
throw throwableObject;
− A throwable object is an instance of class Throwable or subclass
of the Throwable class.
− Example 2: Java throw keyword
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Please enter your roll number: ");
int roll = s.nextInt();
if(roll < 0) throw new ArithmeticException("Roll number can't be negative");
else System.out.println("Valid roll number");
}
}
Exception Handling …
− Example 3: Throwing checked exception
import java.io.*;
class Main {
public static void findFile() throws IOException {
throw new IOException("File not found");
}
public static void main(String[] args) {
try {
findFile();
System.out.println("Rest of code in try block");
} catch (IOException e) {
System.out.println(e.getMessage());
} Output:
} File not found
}
− The findFile() method throws an IOException with the message we
passed to its constructor.
− Note that since it is a checked exception, we must specify it in the throws clause.
− The methods that call this findFile() method need to either handle this
exception or specify it using throws keyword themselves.
− We have handled this exception in the main() method. The flow of program
execution transfers from the try block to catch block when an exception is
thrown. So, the rest of the code in the try block is skipped and statements in the
Differences between Throw and
Throws
Topic Throw keyword Throws keyword
Definition throw keyword is used to throw throws keyword is used in the method
an exception explicitly in the signature to declare an exception which
code, inside the method or the might be thrown by the method while
block of code. the execution of the code.
Propagation Type of exception using throw Using throws keyword, we can declare
of Exceptions keyword, we can only propagate both checked and unchecked
unchecked exception i.e., the exceptions. However, the throws
checked exception cannot be keyword can be used to propagate
propagated using throw only. checked exceptions only.

Syntax The throw keyword is followed The throws keyword is followed by the
by throwable object. class name of exceptions that is going to
be thrown.
// throwing Exception // throws keyword multiple exception
throw throwableObject; // handling
void test_method() throws
<ExceptionClassname1> ,
<ExceptionClassname2 > , .. {
// statement that might raise exception
}
Differences between Throw and
Throws …
Topic Throw keyword Throws keyword
Declaration throw is used within the throws is used with the method
method. signature.
Internal We are allowed to throw only We can declare multiple exceptions
Implementation one exception at a time i.e. using throws keyword that can be
we cannot throw multiple thrown by the method. For example,
exceptions. … main() throws IOException,
SQLException {
}

❖ An exception is first thrown from the top of the stack & if it is not
caught, it drops down the call stack to the previous method. If not
caught there, the exception again drops down to the previous method,
& so on until they are caught or until they reach the very bottom of the
call stack. This is called exception propagation.
Exception Propagation Example
class TestExceptionPropagation {
void m(){
int data = 50/0;
}
void n(){
m();
}
void p(){
try {
n();
}catch(Exception e){System.out.println("Exception handled");}
}
public static void main(String args[]){
TestExceptionPropagation obj = new TestExceptionPropagation();
obj.p();
System.out.println("Normal flow ...");
}
}
Output:
Exception handled
Normal flow ...
Exception Propagation Example …
• In the above example exception occurs in the m() method
where it is not handled, so it is propagated to the previous
n() method where it is not handled, again it is propagated
to the p() method where exception is handled.
• Exception can be handled in any method in call stack
either in the main() method, p() method, n() method or
m() method.
File Handling
What is File Handling?
• It is the process of working with files on your computer.
Files are used to store data, such as text, images, or any
other type of information.
• In Java, you can read data from files or write data to files
using the built-in features of the language.
• Assume you have a text file containing a list of names.
– With file handling in Java, you can read those names from the file
and display them on the screen. Similarly, you can write new
names to the file, and they will be saved for future use.
• File handling is essential for many programs, as it allows
you to store and retrieve data from external sources like
files, or databases, making your Java programs more
powerful and versatile.
How File Handling Works?
• Here’s a simple explanation of how file handling works in
Java:
• Reading from a file:
– When you want to read information from a file, you can use
Java to open the file, read its contents, and then do
something with that data.
– It is like opening a book, reading the text, and
understanding what's written inside.
• Writing to a file:
– On the other hand, if you want to save some information to
a file, you can use Java to create a new file, write data into
it, and save it on your computer.
– It is like writing a letter or a story and keeping it for later.
Types of Files
• Java files can be classified into two main types based on
the data they store.
• Text Files:
− They are files that store data in plain text format. They contain
human-readable characters, such as letters, numbers, symbols, and
spaces.
− They can be opened and read using a simple text editor, and their
content can be easily understood by humans. In Java, text files are
commonly used for storing configuration data, logs, and other textual
information.
• Binary Files:
− They store data in a format that is not directly human-readable. They
consist of sequences of bytes that represent various types of data,
such as images, audio, video, or compiled programs.
− They cannot be easily understood by humans, as they require specific
software or applications to interpret their contents correctly.
File Paths
• In computer systems, a file path is a string that specifies
the location of a file or directory within a file system.
– It serves as a unique address, guiding the operating system
on how to access and locate the desired file or folder.
– They are used to navigate through the directory structure,
allowing programs to interact with files in a structured and
organized manner.
– File paths can be absolute or relative.
• Absolute file path:
– It provides the complete and full location of a file or
directory starting from the root of the file system.
– It includes all the necessary information needed to locate
the file or directory without any ambiguity.
– For example: C:\Users\Abel\Documents\file.txt
File Paths …
• Relative file path:
– It specifies the location of a file or directory relative to the
current working directory of the program or user.
– It is shorter and more convenient than an absolute path, as
it assumes the context of the program’s current position in
the directory structure.
– They are often used when the file or directory is located
within the same folder or a known subfolder.
– For example:
▪ If the current working directory is "C:\Users\Abel", a
relative path might look like "Documents\file.txt".
Components of File Path
• File paths can include various components, separated by
specific characters.
• File separator:
– It is the character that separates directories and files in the file
path. For Windows systems, it is usually backslash \, and for Unix-
like systems (including macOS and Linux), it is the forward slash /.
• Directory names:
− These are the names of the directories leading to the file,
arranged hierarchically. For example, in the path
"C:\Users\Abel\Documents\file.txt", "Users“, “Abel“ and
“Documents” are directory names.
• File name:
− This is the name of the specific file itself, which comes after the
last directory in the path. In the above example, "file.txt" is the
file name.
File Class
• The File class of the java.io package is used to
perform various operations on files and directories.
• Creating a Java File Object:
– To create an object of File, we need to import the
java.io.File package first.
– Once we import the package, here is how we can create objects
of file.
// creates an object of File using the path
File f = new File(String pathName);
– Here, we have created a file object named f. The object can be
used to work with files and directories.
– Note: In Java, creating a file object does not mean creating a file.
Instead, a file object is an abstract representation of the file or
directory pathname (specified in the parenthesis).
File Class Methods
• canRead():
– It checks whether the file is readable or not & returns a Boolean
value i.e., true or false.
• canWrite():
– It checks whether the file is writable or not & returns a Boolean
value i.e., true or false.
• exists():
– It is used to check whether the given file is present or not &
returns a Boolean value.
• createNewFile():
− When we want to create a new empty file, use this file class
method. It returns a Boolean value.
• delete():
− It is used for deleting a file & returns a Boolean value.
File Class Methods …
• getAbsolutePath():
– It is used to return the absolute pathname of the file.
• getName():
– It is used to return a string value which is the name of the file.
• list():
– It returns an array of strings representing all the files in the
directory.
• length():
– This method of the file class returns the file’s size in bytes.
• mkdir():
– It is a method of file class that is used to create a new directory.
• renameTo():
– It is used to rename the abstract path name of a File to a given
path name.
File Operations
• You can perform various file operations in Java to manage
files and directories on your computer.
• Let’s understand these operations with the respective file
handling programs in Java.
– Creating a file
– Checking if a file exists
– Renaming a file
– Writing to a file
– Reading from a file
– Copying a file
– Moving a file
– Creating a directory
– Listing files in a directory
– Deleting a file
– Getting information of a file
Creating a File
• In Java, we can create a file using the
createNewFile() method of the File class. This
method returns true if the file is created, otherwise, false
is returned if the file already exists. For example,
import java.io.File;
import java.io.IOException;

class Main {
public static void main(String[] args) throws IOException {
// an object of file class
File f = new File("demo.txt");

// creating a new file


Boolean result = f.createNewFile();

if(result == true) System.out.print(f+" created successfully.");


else System.out.println("File cannot be created due to some error.");
}
}
Checking if a File Exists
• You can check if a file exists on your system using the
File class and its exists() method. For example,
import java.io.File;

class Main {
public static void main(String[] args) {
File f = new File("demo.txt");

if(f.exists() == true) System.out.println("File exists!");


else System.out.println("File does not exist.");
}
}
Renaming a File
• You can rename a file using the File class and its
renameTo() method, which allows you to change the
name of the file. For example,
import java.io.File;

class Main {
public static void main(String[] args) {
File oldFile = new File("demo.txt");
File newFile = new File("newDemo.txt");

if(oldFile.renameTo(newFile) == true)
System.out.println("File renamed successfully!");
else
System.out.println("File renaming failed.");
}
}
Writing to a File
• The write operation on a file means storing the data in a
file.
• To perform write operations on a file, we will use the
write() method along with the FileWriter class.
• Why is the close() method appropriate to use?
Because closing a writer deallocates any value in it or any
resources associated with it. For example,
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

class Main {
public static void main(String[] args) throws IOException {
String str = "Welcome to File Handling in Java!";
FileWriter fw = new FileWriter(“newDemo.txt");
fw.write(str);
fw.close(); // closing a file
}
}
Reading a File
• The read operation means accessing or retrieving the data
stored from a file.
• To perform a read operation on a file, we will use the
Scanner class along with the hasNextLine() and
nextLine() methods to retrieve data from a file. For
example,
import java.io.File;
import java.io.IOException;
import java.util.Scanner;

class Main {
public static void main(String[] args) throws IOException {
File f = new File(“newDemo.txt");
Scanner input = new Scanner(f);
while(input.hasNextLine() == true) {
String str = input.nextLine();
System.out.println(str);
}
input.close(); // closing a file
}
}
Copying a File
• You can copy the contents of one file to another using
input and output streams. This operation duplicates the
data from one file to another. For example,
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

class Main {
public static void main(String[] args) throws IOException{
File src = new File(“newDemo.txt");
File dest = new File("New/destination.txt");

Files.copy(src.toPath(), dest.toPath());
}
}
Moving a File
• Moving a file involves both copying it to a new location
and deleting the original file. This can be achieved using
the renameTo() method. For example,
import java.io.File;

class Main {
public static void main(String[] args) {
File sourceFile = new File("newdemo.txt");
File destinationFile = new File("New/newDemo.txt");

if(sourceFile.renameTo(destinationFile) == true)
System.out.println("File moved successfully!");
else
System.out.println("File moving failed.");
}
}
Creating a Directory
• To create a new directory (folder) in your file system, you
can use the mkdir() method of the File class. For
example,
import java.io.File;

class Main {
public static void main(String[] args) {
File directory = new File("newDirectory");

if(directory.mkdir() == true)
System.out.println("Directory created successfully!");
else
System.out.println("Directory creation failed.");
}
}
Listing Files in a Directory
• You can list all the files and subdirectories present in a
directory using the list() or listFiles() method
of the File class.
import java.io.File;

class Main {
public static void main(String[] args) {
File directory = new File("New");
String[] fileList = directory.list();

for(String fileName: fileList)


System.out.println(fileName);
}
}
Deleting a File
• In file handling, we can delete a file using the delete()
method of the File class.
• There is no need to close the file using close() because
neither the FileWriter nor the Scanner classes are
used to delete a file. For example,
import java.io.File;
import java.io.IOException;

class Main {
public static void main(String[] args) throws IOException {
File f = new File("demo.txt");
Boolean result = f.delete(); // To delete a file

if(result == true) System.out.print(f + " deleted successfully.");


else System.out.format("File cannot be deleted due to some error.");
}
}
Getting File Information
• There are few methods in Java that I have discussed
earlier at methods of file class to get the information of
the file.
import java.io.File;
import java.io.IOException;

class Main {
public static void main(String[] args) throws IOException {
File f = new File("demo.txt");
f.createNewFile();
String filename = f.getName();

System.out.println("File Name is " + filename);


System.out.println("Absolute path of " + filename + ": " + f.getAbsolutePath());
System.out.print("length of " + filename + ": " + f.length());
System.out.println("\nIs " + filename + " readable? " + f.canRead());
System.out.println("Is " + filename + " writable? " + f.canWrite());
System.out.println("Is " + filename + " exists? " + f.exists());
}
} Sample output:
File Name is demo.txt
Absolute path of demo.txt: C:\Users\hp\Desktop\JavaCodes\demo.txt
length of demo.txt: 0
Is demo.txt readable? true
Is demo.txt writable? true
Is demo.txt exists? true
Thank You!

You might also like