Unit 4: Exception and IO
Unit 4: Exception and IO
Exceptions
Exception hierarchy-throwing and catching exceptions-built-in exceptions, creating own exceptions,
Stack Trace Elements. Input /Output Basics-Streams-Byte streams and character streams-Reading
and Writing Console-Reading and Writing Files Templates
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
• DivideByZero exception
• NullPointerException
• ArithmeticException
• ArrayIndexOutOfBoundsException
1. An exception (or exceptional event) is a problem that arises during the execution of a
program.
2. 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.
3. 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.
Key words used in Exception handling
There are 5 keywords used in java exception handling.
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.
3. finally
A finally block of code always executes, irrespective of occurrence of an Exception.
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 is used to postpone the handling of a checked exception.
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 stacktrace 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 as 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.
Throw
it is possible for your program to throw an exception explicitly, using the throw statement. The
general form of throw is shown here:
throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
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.
// 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);
}
}
}
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 behaviour
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. This is the general form of a method declaration that includes a
throws clause:
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.
Categories 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.
IO IN JAVA
Java I/O (Input and Output) is used to process the input and produce
the output based on the input. Java uses the concept of stream to make
I/O operation fast. The java.io package contains all the classes
required for input and output operations.
Stream
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 adestination.
Byte Streams: Java byte streams are used to perform input and output of 8-bit bytes
FileInputStream , FileOutputStream.
Character Streams: Java Character streams are used to perform input and output for 16-bit
unicode.
FileReader , FileWriter
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 to 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 to standard error stream and represented as System.err.
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.
Example:
import
java.io.*;
class C{
public static void main(String args[])throws
Exception{ FileInputStream fin=new
FileInputStream("C.java"); FileOutputStream
fout=new FileOutputStream("M.java"); int i=0;
while((i=fin.read())!=-
1){ fout.write((byte)i);
}
fin.close();
}
}
Byte Stream
Byte streams process data byte by byte (8 bits). For example FileInputStream is
used to read from source and FileOutputStream to write to the destination.
// Java Program illustrating the Byte Stream to copy
// contents of one file to another file.
importjava.io.*;
publicclassBStream
{
Public static void main(String[] args) throws IOException
{
FileInputStream sourceStream = null;
FileOutputStream targetStream = null;
try
{
sourceStream = newFileInputStream("sorcefile.txt");
targetStream = newFileOutputStream ("targetfile.txt");
// Reading source file and writing content to target
// file byte by byte
inttemp;
while((temp = sourceStream.read()) != -1)
targetStream.write((byte)temp);
}
finally
{
if(sourceStream != null)
sourceStream.close();
if(targetStream != null)
targetStream.close();
}
}
}
Final Keyword In Java – Final variable, Method and Class
final keyword can be used along with variables, methods and classes.
1) final variable
2) final method
3) final class
final variable
final variables are nothing but constants. We cannot change the value of a final
variable once it is initialized. Lets have a look at the below code:
classDemo{
finalint MAX_VALUE=99;
void myMethod(){
MAX_VALUE=101;
}
Public static void main(String args[]){
Demo obj=newDemo();
obj.myMethod();
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The final field Demo.MAX_VALUE cannot be assigned
at beginnersbook.com.Demo.myMethod(Details.java:6)
at beginnersbook.com.Demo.main(Details.java:10)
We got a compilation error in the above program because we tried to change the
value of a final variable “MAX_VALUE”.
final method
A final method cannot be overridden. Which means even though a sub class can
call the final method of parent class without any issues but it cannot override it.
Example:
class XYZ{
finalvoid demo(){
System.out.println("XYZ Class Method");
}
}
class ABC extends XYZ{
void demo(){
System.out.println("ABC Class Method");
}
public static void main(String args[]){
ABC obj=new ABC();
obj.demo();
}
}
The above program would throw a compilation error, however we can use the
parent class final method in sub class without any issues. Lets have a look at
this code: This program would run fine as we are not overriding the final
method. That shows that final methods are inherited but they are not eligible for
overriding.
class XYZ{
finalvoid demo(){
System.out.println("XYZ Class Method");
}
}
class ABC extends XYZ{
public static void main(String args[]){
ABC obj=new ABC();
obj.demo();
}
}
Output:
XYZ ClassMethod
final class
We cannot extend a final class. Consider the below example:
finalclass XYZ{
}
class ABC extends XYZ{
void demo(){
System.out.println("My Method");
}
Public static void main(String args[]){
ABC obj=new ABC();
obj.demo();
}
}
Output:
The type ABC cannot subclass the final class XYZ