[go: up one dir, main page]

0% found this document useful (0 votes)
40 views11 pages

Chapter 3

This document discusses file and exception handling in Java. It defines exceptions as problems that disrupt normal program flow and explains that exceptions must be handled to prevent programs from terminating abnormally. It describes different types of exceptions like checked exceptions that must be declared and unchecked exceptions like NullPointerException. It also covers exception handling techniques like try/catch blocks to gracefully handle exceptions, and finally blocks to ensure cleanup code always executes.

Uploaded by

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

Chapter 3

This document discusses file and exception handling in Java. It defines exceptions as problems that disrupt normal program flow and explains that exceptions must be handled to prevent programs from terminating abnormally. It describes different types of exceptions like checked exceptions that must be declared and unchecked exceptions like NullPointerException. It also covers exception handling techniques like try/catch blocks to gracefully handle exceptions, and finally blocks to ensure cleanup code always executes.

Uploaded by

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

CHAPTER 3

FILE AND EXCEPTION HANDLING


What is Exception?
An exception (or exceptional event) is a problem that arises during the execution of a program.
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.
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.
Types of Exceptions
In Java, exceptions broadly can be categories into checked exception, unchecked exception and
error based on the nature of exception.
• Checked Exception
The exception that can be predicted by the JVM at the compile time for example: File that
need to be opened is not found, SQLException etc. These types of exceptions must be
checked at compile time.
• Unchecked Exception
Unchecked exceptions are the class that extends RuntimeException class. Unchecked
exceptions are ignored at compile time and checked at runtime. For example:
ArithmeticException, NullPointerException, Array Index out of Bound exception.
Unchecked exceptions are checked at runtime.
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.
Exception Handling
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors/exceptions so that normal flow of the application can be maintained.
try and catch in Java
Syntax of try catch
try
{
// Protected code
}
catch (ExceptionName e1)
{
// Catch block
}
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
If an exception occurs at the particular statement of try block, the rest of the block code will not
execute. So, it is recommended not to keeping the code in try block that will not throw an
exception.
Java catch block
Java catch block is used to handle the Exception by declaring the type of exception within the
parameter. The declared exception must be the parent class exception ( i.e., Exception) or the
generated exception type. However, the good approach is to declare the generated type of
exception.
Problem without exception handling
Let's try to understand the problem if we don't use a try-catch block.
public class TryCatchExample1 {
public static void main(String[] args) {
int data=50/0; //may throw exception
System.out.println("rest of the code");
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Solution by exception handling
Let's see the solution of the above problem by a java try-catch block.
public class TryCatchExample2 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Multiple catch blocks
A try block can be followed by multiple catch blocks. It means we can have any number of catch
blocks after a single try block. If an exception occurs in the guarded code(try block) the exception
is passed to the first catch block in the list. If the exception type matches with the first catch block
it gets caught, if not the exception is passed down to the next catch block. This continue until the
exception is caught or falls through all catches.
Multiple Catch Syntax
To declare the multiple catch handler, we can use the following syntax.
try
{
// suspected code
}
catch(Exception1 e)
{
// handler code
}
catch(Exception2 e)
{
// handler code
}
Now lets see an example to implement the multiple catch block that are used to catch possible
exception.
The multiple catch blocks are useful when we are not sure about the type of exception during
program execution.
Examples for Multiple Catch blocks
In this example, we are trying to fetch integer value of an Integer object. But due to bad input, it
throws number format exception.
class Demo{
public static void main(String[] args) {
try
{
Integer in = new Integer("abc");
in.intValue();
}
catch (ArithmeticException e)
{
System.out.println("Arithmetic " + e);
}
catch (NumberFormatException e)
{
System.out.println("Number Format Exception " + e);
}
}
}
Java throw, throws and finally Keyword
Throw, throws and finally are the keywords in Java that are used in exception handling. The
throw keyword is used to throw an exception and throws is used to declare the list of possible
exceptions with the method signature. Whereas finally block is used to execute essential code,
specially to release the occupied resources.
Now lets discuss each in details with the examples.
Java Throw
The throw keyword is used to throw an exception explicitly. Only object of Throwable class or
its sub classes can be thrown. Program execution stops on encountering throw statement, and
the closest catch statement is checked for matching type of exception.
Syntax :
throw ThrowableInstance
Creating Instance of Throwable class
We allows to use new operator to create an instance of class Throwable,
new NullPointerException("test");
This constructs an instance of NullPointerException with name test.
Example throw Exception
In this example, we are throwing Arithmetic exception explicitly by using the throw keyword
that will be handle by catch block.
class Test
{
static void avg()
{
try
{
throw new ArithmeticException("demo");
}
catch(ArithmeticException e)
{
System.out.println("Exception caught");
}
}
public static void main(String args[])
{
avg();
}
}
In the above example the avg() method throw an instance of ArithmeticException, which is
successfully handled using the catch statement and thus, the program prints the output
"Exception caught".
Java throws Keyword
The throws keyword is used to declare the list of exception that a method may throw during
execution of program. Any method that is capable of causing exceptions must list all the
exceptions possible during its execution, so that anyone calling that method gets a prior
knowledge about which exceptions are to be handled. A method can do so by using
the throws keyword.
Syntax:
type method_name(parameter_list) throws exception_list
{
// definition of method
}
Example throws Keyword
Here, we have a method that can throw Arithmetic exception so we mentioned that with the
method declaration and catch that using the catch handler in the main method.
class Test
{
static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}
public static void main(String args[])
{
try
{
check();
}
catch(ArithmeticException e)
{
System.out.println("caught" + e);
}
}
}
finally clause
A finally keyword is used to create a block of code that follows a try block. A finally block of code
is always executed whether an exception has occurred or not. Using a finally block, it lets you
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 catch block.

Example finally Block


In this example, we are using finally block along with try block. This program throws an
exception and due to exception, program terminates its execution but see code written inside
the finally block executed. It is because of nature of finally block that guarantees to execute the
code.
Class ExceptionTest
{
public static void main(String[] args)
{
int a[] = new int[2];
System.out.println("out of try");
try
{
System.out.println("Access invalid element"+ a[3]);
/* the above statement will throw ArrayIndexOutOfBoundException */
}
finally
{
System.out.println("finally is always executed.");
}
}
}

File Handling
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the
classes required for input and output operations.
We can perform file handling in Java by Java I/O API.
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because
it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with the
console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
Let's see the code to print output and an error message to the console.
System.out.println("simple message" );
System.err.println("error message" );
Let's see the code to get input from console.
int i=System.in.read();//returns ASCII code of 1st character
System.out.println((char)i);//will print the character
OutputStream vs InputStream
The explanation of OutputStream and InputStream classes are given below:
OutputStream
Java application uses an output stream to write data to a destination; it may be a file, an array,
peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source; it may be a file, an array,
peripheral device or socket.
Let's understand the working of Java OutputStream and InputStream by the figure given below.
OutputStream class
OutputStream class is an abstract class. It is the superclass of all classes representing an output
stream of bytes. An output stream accepts output bytes and sends them to some sink.

OutputStream Hierarchy

InputStream class
InputStream class is an abstract class. It is the superclass of all classes representing an input
stream of bytes.
InputStream Hierarchy

FileOutputStream Class
Java FileOutputStream is an output stream used for writing data to a file.
If you have to write primitive values into a file, use FileOutputStream class. You can write byte-
oriented as well as character-oriented data through FileOutputStream class. But, for character-
oriented data, it is preferred to use FileWriter than FileOutputStream.
FileOutputStream class declaration
Let's see the declaration for Java.io.FileOutputStream class:
public class FileOutputStream extends OutputStream
FileOutputStream Example 1: write byte
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt" );
fout.write(65);
fout.close();
System.out.println("success..." );
}catch(Exception e){System.out.println(e);}
}
}
Output:
Success...
The content of a text file testout.txt is set with the data A.
testout.txt
A
FileInputStream Class
Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented
data (streams of raw bytes) such as image data, audio, video etc. You can also read character-
stream data. But, for reading streams of characters, it is recommended to use FileReader class.
Java FileInputStream class declaration
Let's see the declaration for java.io.FileInputStream class:
public class FileInputStream extends InputStream
FileInputStream example 1: read single character
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt" );
int i=fin.read();
System.out.print((char)i);
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Note: Before running the code, a text file named as "testout.txt" is required to be created. In this
file, we are having following content:
Welcome to javatpoint.
After executing the above program, you will get a single character from the file which is 87 (in
byte form). To see the text, you need to convert it into character.
Output:
W
Java FileInputStream example 2: read all characters
package com.javatpoint;
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt" );
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Output:
Welcome to javaTpoint
FilterReader
Java FilterReader is used to perform filtering operation on reader stream. It is an abstract class
for reading filtered character streams.
The FilterReader provides default methods that passes all requests to the contained stream.
Subclasses of FilterReader should override some of its methods and may also provide additional
methods and fields.
import java.io.*;
class filereader
{
public static void main(String args[])throws Exception
{
try
{
FileReader fin = new FileReader("D:\\sample.txt");
int i=fin.read();
while(i!=-1)
{
System.out.println((char)i);
i=fin.read();
}
fin.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

FilterWriter
Java FilterWriter class is an abstract class which is used to write filtered character streams.
The sub class of the FilterWriter should override some of its methods and it may provide
additional methods and fields also.
import java.io.*;
class filewriter
{
public static void main(String args[])throws Exception
{
try
{
FileReader fin = new FileReader("D:\\sample.txt");
FileWriter fout = new FileWriter("D:\\Test1.txt");
int i=fin.read();
while(i!=-1)
{
fout.write((char)i);
i=fin.read();
}
System.out.println("File Copied succesfully");
fin.close();
fout.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}

********

You might also like