Java Unit - III
Java Unit - III
All the syntax errors (compile time errors) are called as errors.
In Java, an exception is an event that disrupts the normal flow of the program. It is
an object which is thrown at runtime.
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.
Int a[15]={11,22,33,44,55,66,77,88,99,00,111,222,333,444,555};
1. Checked Exception
2. Unchecked Exception
3. Error
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
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.
Output:
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
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.
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.
int a=50/0;//ArithmeticException
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
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:
By the help of custom exception, you can have your own exception and message.
Output:
Exception occured: InvalidAgeException:not valid
rest of the code...
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();
}
}
}
}
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 {
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();
}
}
}
}
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 {
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();
}
}
}
}
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 {
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();
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.