0% found this document useful (0 votes)
59 views19 pages

Java Unit - III

The document discusses exceptions in Java. It defines errors and exceptions, and explains that exceptions are runtime errors while errors are compile-time mistakes. It describes exception handling as a mechanism to maintain normal program flow when exceptions occur. The core types of exceptions are checked and unchecked, with errors considered unchecked exceptions. It provides examples of different exceptions like ArithmeticException and ArrayIndexOutOfBoundsException.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
59 views19 pages

Java Unit - III

The document discusses exceptions in Java. It defines errors and exceptions, and explains that exceptions are runtime errors while errors are compile-time mistakes. It describes exception handling as a mechanism to maintain normal program flow when exceptions occur. The core types of exceptions are checked and unchecked, with errors considered unchecked exceptions. It provides examples of different exceptions like ArithmeticException and ArrayIndexOutOfBoundsException.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 19

UNIT - III

Exception Handling in Java


What is an Error in Java?
Errors are the mistakes done by the programmers while writing a program.

All the syntax errors (compile time errors) are called as errors.

Ex:- semi-colon missing, parenthesis missing, etc..

What is an Exception in Java?


Exception is an abnormal condition.

All the logical errors (runtime errors) are called as exceptions.

In Java, an exception is an event that disrupts the normal flow of the program. It is
an object which is thrown at runtime.

Ex:- Arithmetic overflow , Dividing an integer by zero, etc..

What is an Exception Handling?


Exception Handling is a powerful mechanism to handle runtime errors such as
ClassNotFoundException, IOException, Arithmetic overflow , Dividing an integer by zero,
SQLException, RemoteException, ArrayIndexOutOfBoundsException etc. so that normal flow
of the application can be maintained.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application that is why
we use exception handling. Let's take a scenario:

statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in your program and there occurs an exception at
statement 5, then the rest of the code will not be executed i.e. statement 6 to 10 will not be
executed. If we perform exception handling, the rest of the statement will be executed. That
is why we use exception handling in Java.

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. A hierarchy of Java Exception classes are
given below:
Int a = 5

Int a[15]={11,22,33,44,55,66,77,88,99,00,111,222,333,444,555};

String name[15]={“ JAVED AHAMED”};


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.

Java Exception Keywords


There are 5 keywords which are used in handling exceptions in Java.

Keyword Description

try The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or
finally. It means, we can't use try block alone.

catch The "catch" block is used to handle the exception. It must be preceded
by try block which means we can't use catch block alone. It can be
followed by finally block later.

finally The "finally" block is used to execute the important code of the
program. It is executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It doesn't throw


an exception. It specifies that there may occur an exception in the
method. It is always used with method signature.

Java Exception Handling Example


Let's see an example of Java Exception Handling where we using a try-catch statement to
handle the exception.

public class JavaExceptionExample


{
public static void main(String args[])
{
try
{
//code that may raise exception
int data=100/0;
}
catch (ArithmeticException e)
{
System.out.println(e);
}
//rest code of the program
System.out.println("rest of the code...");
}
}

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero


rest of the code...
class Division {
public static void main(String[] args)
{
int a = 10, b = 5, c = 5, result;
try {
result = a / (b - c);
System.out.println("result" + result);
}

catch (ArithmeticException e) {
System.out.println("Exception caught:Division by zero");
}

finally {
System.out.println("I am in final block");
}
}
}
Output:
Exception caught:Division by zero
I am in final block

Java - Built-in Exceptions


ava 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.
Following is the list of Java Unchecked RuntimeException.

Sr.No. Exception & Description

1 ArithmeticException
Arithmetic error, such as divide-by-zero.

2 ArrayIndexOutOfBoundsException
Array index is out-of-bounds.

3 ArrayStoreException
Assignment to an array element of an
incompatible type.

4 ClassCastException
Invalid cast.

5 IllegalArgumentException
Illegal argument used to invoke a method.

6 IllegalMonitorStateException
Illegal monitor operation, such as waiting on an
unlocked thread.

7 IllegalStateException
Environment or application is in incorrect state.

8 IllegalThreadStateException
Requested operation not compatible with the
current thread state.

9 IndexOutOfBoundsException
Some type of index is out-of-bounds.

10 NegativeArraySizeException
Array created with a negative size.

11 NullPointerException
Invalid use of a null reference.

12 NumberFormatException
Invalid conversion of a string to a numeric
format.

13 SecurityException
Attempt to violate security.

14 StringIndexOutOfBounds
Attempt to index outside the bounds of a string.

15 UnsupportedOperationException
An unsupported operation was encountered.

Following is the list of Java Checked Exceptions Defined in java.lang.

Sr.No. Exception & Description

1 ClassNotFoundException
Class not found.

2 CloneNotSupportedException
Attempt to clone an object that does not
implement the Cloneable interface.
3 IllegalAccessException
Access to a class is denied.

4 InstantiationException
Attempt to create an object of an abstract
class or interface.

5 InterruptedException
One thread has been interrupted by another
thread.

6 NoSuchFieldException
A requested field does not exist.

7 NoSuchMethodException
A requested method does not exist.

Examples of Built-in Exception:

Arithmetic exception : It is thrown when an exceptional condition has occurred in


an arithmetic operation.
// Java program to demonstrate
// ArithmeticException
class ArithmeticException_Demo {
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a / b; // cannot divide by zero
System.out.println("Result = " + c);
}
catch (ArithmeticException e) {
System.out.println("Can't divide a number by 0");
}
}
}
Output:
Can't divide a number by 0
ArrayIndexOutOfBounds Exception : 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.

// Java program to demonstrate


// ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound_Demo {
public static void main(String args[])
{
try {
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index is Out Of Bounds");
}
}
}
Output:
Array Index is Out Of Bounds

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

Creating Own Exception In Java


If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user
need.

By the help of custom exception, you can have your own exception and message.

Let's see a simple example of java custom exception.

class InvalidAgeException extends Exception


{
InvalidAgeException(String s) //constructor
{
super(s);
}
}
class TestCustomException1
{

static void validate(int age)throws InvalidAgeException


{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}catch(Exception m)
{System.out.println("Exception occured: "+m);}

System.out.println("rest of the code...");


}
}

Output:
Exception occured: InvalidAgeException:not valid
rest of the code...

Java - Files and I/O


The java.io package contains nearly every class you might ever need to perform input
and output (I/O) in Java. All these streams represent an input source and an output
destination. The stream in the java.io package supports many data such as primitives,
object, localized characters, etc.

Stream classes in java


A stream can be defined as a sequence of data. There are two kinds of Streams −
• InPutStream − The InputStream is used to read data from a source.
• OutPutStream − The OutputStream is used for writing data to a destination.

Java provides strong but flexible support for I/O related to files and networks but this
tutorial covers very basic functionality related to streams and I/O. We will see the most
commonly used examples one by one −

Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there
are many classes related to byte streams but the most frequently used classes
are, FileInputStream and FileOutputStream. Following is an example which makes
use of these two classes to copy an input file into an output file −
Example
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

Now let's have a file input.txt with the following content −


This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating
output.txt file with the same content as we have in input.txt. So let's put the above code
in CopyFile.java file and do the following −
$javac CopyFile.java
$java CopyFile

Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit Unicode
characters. Though there are many classes related to character streams but the most
frequently used classes are, FileReader and FileWriter. Though internally FileReader
uses FileInputStream and FileWriter uses FileOutputStream but here the major
difference is that FileReader reads two bytes at a time and FileWriter writes two bytes
at a time.
We can re-write the above example, which makes the use of these two classes to copy
an input file (having unicode characters) into an output file −
Example
import java.io.*;
public class CopyFile {

public static void main(String args[]) throws IOException {


FileReader in = null;
FileWriter out = null;

try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

Now let's have a file input.txt with the following content −


This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating
output.txt file with the same content as we have in input.txt. So let's put the above code
in CopyFile.java file and do the following −
$javac CopyFile.java
$java CopyFile

Standard Streams
All the programming languages provide support for standard I/O where the user's
program can take input from a keyboard and then produce an output on the computer
screen. If you are aware of C or C++ programming languages, then you must be aware
of three standard devices STDIN, STDOUT and STDERR. Similarly, Java provides the
following three standard streams −
• Standard Input − This is used to feed the data to user's program and usually a
keyboard is used as standard input stream and represented as System.in.
• Standard Output − This is used to output the data produced by the user's
program and usually a computer screen is used for standard output stream and
represented as System.out.
• Standard Error − This is used to output the error data produced by the user's
program and usually a computer screen is used for standard error stream and
represented as System.err.
Following is a simple program, which creates InputStreamReader to read standard
input stream until the user types a "q" −
Example
import java.io.*;
public class ReadConsole {

public static void main(String args[]) throws IOException {


InputStreamReader cin = null;

try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
}
}
}
}

Reading and Writing Files


As described earlier, a stream can be defined as a sequence of data.
The InputStream is used to read data from a source and the OutputStream is used
for writing data to a destination.
Here is a hierarchy of classes to deal with Input and Output streams.
The two important streams are FileInputStream and FileOutputStream, which would
be discussed in this tutorial.
FileInputStream
This stream is used for reading data from the files. Objects can be created using the
keyword new and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to
read the file −
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read the
file. First we create a file object using File() method as follows −
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
Once you have InputStream object in hand, then there is a list of helper methods which
can be used to read to stream or to do other operations on the stream.

Sr.No. Method & Description

1 public void close() throws IOException{}


This method closes the file output stream. Releases any system resources
associated with the file. Throws an IOException.
2 protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close method
of this file output stream is called when there are no more references to this
stream. Throws an IOException.

3 public int read(int r)throws IOException{}


This method reads the specified byte of data from the InputStream. Returns an
int. Returns the next byte of data and -1 will be returned if it's the end of the file.

4 public int read(byte[] r) throws IOException{}


This method reads r.length bytes from the input stream into an array. Returns the
total number of bytes read. If it is the end of the file, -1 will be returned.

5 public int available() throws IOException{}


Gives the number of bytes that can be read from this file input stream. Returns
an int.

There are other important input streams available, for more detail you can refer to the
following links −
• ByteArrayInputStream
• DataInputStream

FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would
create a file, if it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to
write the file −
OutputStream f = new FileOutputStream("C:/java/hello")
Following constructor takes a file object to create an output stream object to write the
file. First, we create a file object using File() method as follows −
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
Once you have OutputStream object in hand, then there is a list of helper methods,
which can be used to write to stream or to do other operations on the stream.
Sr.No. Method & Description

1
public void close() throws IOException{}
This method closes the file output stream. Releases any system resources
associated with the file. Throws an IOException.

2
protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close method
of this file output stream is called when there are no more references to this
stream. Throws an IOException.

3
public void write(int w)throws IOException{}
This methods writes the specified byte to the output stream.

4
public void write(byte[] w)
Writes w.length bytes from the mentioned byte array to the OutputStream.

There are other important output streams available, for more detail you can refer to the
following links −
• ByteArrayOutputStream
• DataOutputStream
Example
Following is the example to demonstrate InputStream and OutputStream −
import java.io.*;
public class fileStreamTest {

public static void main(String args[]) {

try {
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("test.txt");
for(int x = 0; x < bWrite.length ; x++) {
os.write( bWrite[x] ); // writes the bytes
}
os.close();

InputStream is = new FileInputStream("test.txt");


int size = is.available();

for(int i = 0; i < size; i++) {


System.out.print((char)is.read() + " ");
}
is.close();
} catch (IOException e) {
System.out.print("Exception");
}
}
}

The above code would create file test.txt and would write given numbers in binary
format. Same would be the output on the stdout screen.

You might also like