Java Unit 3
Java Unit 3
Exception:
The Exception Handling in Java is one of the powerful mechanisms to handle the runtime errors
so that the normal flow of the application can be maintained.
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 need to handle
exceptions. Let's consider 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 a Java program and an exception occurs at statement 5; the
rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However,
when we perform exception handling, the rest of the statements will be executed. That is why we
use exception handling in Java.
Errors indicate serious problems and abnormal conditions that most applications should not try
to handle. Error defines problems that are not expected to be caught under normal
circumstances by our program. For example, memory error, hardware error, JVM error etc.
Exceptions
are conditions within the code. A developer can handle such conditions and take necessary
corrective actions. Few examples
DivideByZeroException
NullPointerException
ArithmeticException
ArrayIndexOutOfBoundsException
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. If an exception is raised, which has not been handled by
programmer then program execution can get terminated and system prints a non-user-friendly
error message.
Ex: Exception in thread "main" java.lang.ArithmeticException: / by
zero at ExceptionDemo.main(ExceptionDemo.java:5)
Where, ExceptionDemo : The class name
main : The method name
ExceptionDemo.java : The filename
java:5 : Line number
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.
Exception Hierarchy
All exception classes are subtypes of the java. lang. Exception class. The exception class is a
subclass of the Throwable class.
1. try A try/catch block is placed around the code that might generate an exception. Code
within a try/catch block is referred to as protected code.
2. catch A catch statement involves declaring the type of exception we are trying to catch.
4. throw It is used to execute important code such as closing connection, stream etc. Throw is
used to invoke an exception explicitly.
5. throws throws are used to postpone the handling of a checked exception.
This small program includes an expression that intentionally causes a divide-by-zero error: class
Exc0 {public static void main (String args []) {int d = 0; int a = 42 / d;} } When the Java run-
time system detects the attempt to divide by zero, it constructs a new exception object and then
throws this exception. This causes the execution of Exc0 to stop, because once an exception has
been thrown, it must be caught by an exception handler and dealt with immediately
Any exception that is not caught by your program will ultimately be processed by the default
handler. The default handler displays a string describing the exception, prints a stack trace from
the point at which the exception occurred, and terminates the program. Here is the exception
generated when this example is executed:
Stack Trace:
Stack Trace is a list of method calls from the point when the application was started to the point
where the exception was thrown. The most recent method calls are at the top. A stack trace is a
very helpful debugging tool. It is a list of the method calls that the application was in the middle
of when an Exception was thrown. This is very useful because it doesn't only show you where
the error happened, but also how the program ended up in that place of the code.
Using try and Catch
To guard against and handle a run-time error, simply enclose the code that you want to monitor
inside a try block. Immediately following the try block, include a catch clause that specifies the
exception type that you wish to catch. A try and its catch statement form a unit. The following
program includes a try block and a catch clause that processes the ArithmeticException
generated by the division-by-zero error:
Example:
class Exc2 {
public static void main (String args []) {
int d, a;
try {// monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
Output:
Division by zero.
After catch statement.
The call to println () inside the try block is never executed. Once an exception is thrown,
program control transfers out of the try block into the catch block.
In some cases, more than one exception could be raised by a single piece of code. To handle this
type of situation, you can specify two or more catch clauses, each catching a different type of
exception. When an exception is thrown, each catch statement is inspected in order, and the first
one whose type matches that of the exception is executed. After one catch statement executes,
the others are bypassed, and execution continues after the try/catch block.
Example:
The following example traps two different exception types:
// Demonstrate multiple catch statements.
class MultiCatch {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
Output:
Here is the output generated by running it both ways:
C:\>java MultiCatch
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:\>java MultiCatch TestArg
a=1
Array index oob: java.lang.ArrayIndexOutOfBoundsException:42
After try/catch blocks.
Example:
// An example of nested try statements.
class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
/* If no command-line args are present,
the following statement will generate
a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
/* If one command-line arg is used,
then a divide-by-zero exception
will be generated by the following code. */
if(a==1) a = a/(a-a); // division by zero
/* If two command-line args are used,
then generate an out-of-bounds exception. */
if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}
Output:
C:\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One
a=1
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One Two
a=2
Array index out-of-bounds: java. lang. ArrayIndexOutOfBoundsException:42
Throw
it is possible for your program to throw an exception explicitly, using the throw statement.
Syntax:
throw ThrowableInstance;
Primitive types, such as int or char, as well as non-Throwable classes, such as String and Object,
cannot be used as exceptions. There are two ways you can obtain a Throwable object: using a
parameter in a catch clause, or creating one with the new operator.
The flow of execution stops immediately after the throw statement; any subsequent statements
are not executed. The nearest enclosing try block is inspected to see if it has a catch statement
that matches the type of exception. If it does find a match, control is transferred to that statement.
If not, then the next enclosing try statement is inspected, and so on. If no matching catch is
found, then the default exception handler halts the program and prints the stack trace.
Example:
// Demonstrate throw.
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}
Output:
Here is the resulting output:
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo
Throws
If a method is capable of causing an exception that it does not handle, it must specify this
behavior so that callers of the method can guard themselves against that exception. You do this
by including a throws clause in the method’s declaration. A throws clause lists the types of
exceptions that a method might throw. This is necessary for all exceptions, except those of type
Error or RuntimeException, or any of their subclasses. All other exceptions that a method can
throw must be declared in the throws clause.
Syntax:
type method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method can throw
Example:
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
Output:
inside throwOne
caught java.lang.IllegalAccessException: demo
finally
The finally keyword is designed to address this contingency. finally creates a block of code that
will be executed after a try/catch block has completed and before the code following the
try/catch block. The finally block will execute whether or not an exception is thrown. If an
exception is thrown, the finally block will execute even if no catch statement matches the
exception. Any time a method is about to return to the caller from inside a try/catch block, via an
uncaught exception or an explicit return statement, the finally clause is also executed just before
the method returns. This can be useful for closing file handles and freeing up any other resources
that might have been allocated at the beginning of a method with the intent of disposing of them
before returning. The finally clause is optional.
Example:
// Demonstrate finally.
class FinallyDemo {
// Through an exception out of the method.
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");
}
}
// Return from within a try block.
static void procB() {
try {
System.out.println("inside procB");
return;
} finally {
System.out.println("procB's finally");
}
}
// Execute a try block normally.
static void procC() {
try {
System.out.println("inside procC");
} finally {
System.out.println("procC's finally");
}
}
public static void main(String args[]) {
try {
procA();
} catch (Exception e) {
System.out.println("Exception caught");
}
procB();
procC();
}
}
Output:
inside procA
procA’s finally
Exception caught
inside procB
procB’s finally
inside procC
procC’s finally
Types 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.
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.
Error
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, Assertion Error etc.
Built-in exceptions are the exceptions which are available in Java libraries. These exceptions are
suitable to explain certain error situations.
Output:
Can't divide a number by 0
} class Geeks {
} class MyClass {
public static void main(String[] args)
{
Object o = class.forName(args[0]).newInstance();
System.out.println("Class created for" + o.getClass().getName());
}
}
Output:
ClassNotFoundException
4. FileNotFoundException: This Exception is raised when a file is not accessible or does not
open.
}
Output:
Output:
NullPointerException.
System.out.println(num);
}
catch (NumberFormatException e) {
System.out.println("Number format exception");
}
}
}
Output:
10. ClassCastException
Output:
User-defined Exceptions
All exceptions must be a child of Throwable.
If we want to write a checked exception that is automatically enforced by the
Handle ,we need to extend the Exception class.
User defined exception needs to inherit (extends) Exception class in order to act as
an exception.
throw keyword is used to throw such exceptions.
class EmployeeTest
{
static void employeeAge(int age) throws MyOwnException
{
if(age < 0)
throw new MyOwnException("Age can't be less than zero");
else
System.out.println("Input is valid!!");
}
public static void main(String[] args)
{
try { employeeAge(-2);
}
catch (MyOwnException e)
{
e.printStackTrace();
}
}
}
Exception handling allows us to control the normal flow of the program by using
exception handling in program.
It throws an exception whenever a calling method encounters an error providing that the
calling method takes care of that error.
It also gives us the scope of organizing and differentiating between different error types
using a separate block of codes. This is done with the help of try-catch blocks.
To process the input and generate an output, Java I/O (Input and Output) is used.
Java utilizes the stream idea to speed up the I/O operation. The java.io package includes
all the classes which are necessary for input and output operations. We can use Java I/O
API to handle files.
The java.io package contains almost every class in Java that you may ever need to
perform input and output (I / O). All these streams are a source of input and a destination
of output. The stream in the java.io package supports a lot of information like primitives,
object, localized characters, etc.
Stream
A stream can be described as a data sequence. There are two types of streams available:
Byte Streams
Java byte streams are used to execute 8-bit bytes input and output. Although there are
many classes linked to byte streams, FileInputStream and FileOutputStream are the
most commonly used classes. Following is an instance to copy an input file into an output
file using these two classes.
Example:
import java.io.*;
public class FileCopyExample {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("inputFile.txt");
out = new FileOutputStream("outputFile.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Character Streams
Java Byte streams are used to execute 8-bit bytes input and output while Java Character
streams are used to execute 16-bit Unicode input and output. Although there are many
classes associated with character streams, FileReader and FileWriter are the most
commonly used classes. While FileReader utilizes FileInputStream internally and
FileWriter uses FileOutputStream, the main distinction here is that FileReader reads two
bytes at one moment and FileWriter writes two bytes at one moment.
The above instance can be re-written, which makes use of these two classes to copy an
input file (with Unicode characters) into an output file.
import java.io.*;
public class FileCopyExample {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("inputFile.txt");
out = new FileWriter("outputFile.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Java Standard Streams
All Java programs automatically import the java.lang package. This package defines a class
called System, which encapsulates several aspects of the run-time environment. For example,
using some of its methods, we can obtain the current time and the settings of various properties
associated with the system. System class also contains three predefined stream variables, in,
out, and err. These fields are declared as public and static within System. This means that they
can be used by any other part of our program and without reference to a
specific System object. System.out refers to the standard output stream. By default, this is the
console. System.in refers to standard input, which is the keyboard by default. System.err refers
to the standard error stream, which also is the console by default. However, these streams may be
redirected to any compatible I/O device. System.in is an object of
type InputStream; System.out and System.err are objects of type PrintStream. These are byte
streams, even though they typically are used to read and write characters from and to the console.
We can wrap these within character-based streams, if desired. The preceding chapters have been
using System.out in their examples. We can use System.err in much the same way.
Standard Input: Accessed through in which is used to read input from the keyboard.
Standard Output: Accessed through out which is used to write output to the display
(console).
Standard Error: Accessed through err which is used to write error output to the display
(console).
These objects are defined automatically and do not need to be opened explicitly. Standard
Output and Standard Error, both are to write output; having error output separately so that the
user may read error messages efficiently.
System.in is a byte stream that has no character stream features. To use Standard Input as a
character stream, wrap System.in within the InputStreamReader as an argument.
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.
Below is a basics program, which creates InputStreamReader to read standard input stream until
the user types a "p".
Example:
import java.io. *;
try {
char c;
do {
c = (char) cin.read();
System.out.print(c);
} finally {
if (cin != null) {
cin.close();
}
}
import java.io.FileOutputStream;
try{
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
Output:
Success...
testout.txt
import java.io.FileOutputStream;
try{
fout.write(b);
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 Welcome to java
testout.txt
Welcome to java.
Welcome to java
import java.io.*;
public class BufferedOutputStreamExample{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to java.";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}
Output:
Success
testout.txt
Welcome to java.
Welcome java
Output:
Welcome java
Declaration
public class ByteArrayOutputStream extends OutputStream
bout.flush();
bout.close();//has no effect
System.out.println("Success...");
}
}
Output:
Success...
f1.txt:
A
f2.txt:
A
import java.io.*;
public class ReadExample {
public static void main(String[] args) throws IOException {
byte[] buf = { 35, 36, 37, 38 };
// Create the new byte array input stream
ByteArrayInputStream byt = new ByteArrayInputStream(buf);
int k = 0;
while ((k = byt.read()) != -1) {
//Conversion of a byte into character
char ch = (char) k;
System.out.println("ASCII value of Character is:" + k + "; Special character is: " + ch);
}
}
}
Output:
import java.io.*;
public class OutputExample {
public static void main(String[] args) throws IOException {
FileOutputStream file = new FileOutputStream(D:\\testout.txt);
DataOutputStream data = new DataOutputStream(file);
data.writeInt(65);
data.flush();
data.close();
System.out.println("Succcess...");
}
}
Output:
Succcess...
testout.txt:
A
import java.io.*;
public class DataStreamExample {
public static void main(String[] args) throws IOException {
InputStream input = new FileInputStream("D:\\testout.txt");
DataInputStream inst = new DataInputStream(input);
int count = input.available();
byte[] ary = new byte[count];
inst.read(ary);
for (byte bt : ary) {
char k = (char) bt;
System.out.print(k+"-");
}
}
}
Here, we are assuming that you have following data in "testout.txt" file:
JAVA
Output:
J-A-V-A
Example:
import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
Here, we are assuming that you have following data in "testout.txt" file:
Welcome to java.
Output:
Welcome to java.