Chapter 4 - Exception Handling - Final
Chapter 4 - Exception Handling - Final
− 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
}
}
}
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 {
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");
class Main {
public static void main(String[] args) {
File f = new File("demo.txt");
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();
class Main {
public static void main(String[] args) throws IOException {
File f = new File("demo.txt");
Boolean result = f.delete(); // To delete a file
class Main {
public static void main(String[] args) throws IOException {
File f = new File("demo.txt");
f.createNewFile();
String filename = f.getName();