Java Unit 3
Java Unit 3
Exception handling :
• Exception handling Fundamentals, Exception types
• Uncaught exceptions, using try and catch
• multiple catch clauses, nested try statements
• throw, throws and finally
• built- in exceptions
• creating own exception sub classes
WHAT IS EXCEPTION
Dictionary Meaning: Exception is an abnormal condition.
In java, exception is an event that disrupts the normal flow of the
program. It is an object which is thrown at runtime.
Fig . 3.1
COURSE: OOPJ UNIT: 3 Pg. 5
All exception types are subclasses of the built-in class Throwable .
2.Unchecked Exception
occur at the time of execution
Programmer can handle the Exception
Extended by java.lang.RuntimeException class
e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException
3.Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
AssertionError etc.
COURSE: OOPJ UNIT: 3 Pg. 7
UNCAUGHT EXCEPTIONS:
WITHOUT EXCEPTION HANDLING
:public class Testtrycatch1{ WITH EXCEPTION HANDLING
Fig . 3.2
COURSE: OOPJ UNIT: 3 Pg. 9
JAVA MULTIPLE CATCH EXCEPTIONS
In some cases more than on exceptions could be raised by a single
piece of code.
To handle this type of situation ,use two or more catch clauses.
public class TestMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println("task 2 completed");}
catch(Exception e){System.out.println("common task completed");}
System.out.println("rest of the code...");
}
}
Output:
task1 completed
rest of the code...
COURSE: OOPJ UNIT: 3 Pg. 10
JAVA NESTED TRY BLOCK
The try block within a try block is known as nested try block in
java.
WHY USE NESTED TRY BLOCK:
Sometimes a situation may arise where a part of a block may
cause one error and the entire block itself may cause another
error. In such cases, exception handlers have to be nested.
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e)
{System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
COURSE: OOPJ UNIT: 3 Pg. 11
JAVA FINALLY BLOCK
Java finally block is a block that is used to execute important
code such as closing connection, stream etc.
Java finally block is always executed whether exception is handled
or not.
Java finally block follows try or catch block.
Fig . 3.3
COURSE: OOPJ UNIT: 3 Pg. 12
JAVA THROW KEYWORD
throw exception;
Inside the standard package java.lang, Java defines several exception classes.
Java also support to create new exceptions (user define) by using predefine
exceptions.
Hear just define a subclass of Exception class
READING STRINGS
To read a string from the keyboard, use the version of readLine( ) that is a member
of the BufferedReader class. Its general form is shown here:
Console output is most easily accomplished with print( ) and println( ), These methods
are defined by the class PrintStream
Because PrintStream is an output stream derived from OutputStream, it also
implements the low-level method write( ).
Thus, write( ) can be used to write to the console. The simplest form of write( )
defined by PrintStream is shown here:
DEMONSTRATE SYSTEM.OUT.WRITE().
class WriteDemo {
public static void main(String args[]) {
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
}} COURSE: OOPJ UNIT: 3 Pg. 31
THE PRINTWRITER CLASS
PrintWriter is one of the character-based classes. Using a
character-based class for console output makes internationalizing your
program easier.
PrintWriter defines several constructors. The one we will use is
shown here:
PrintWriter( OutputStream outputStream, boolean flushingOn)
PrintWriter supports the print( ) and println( ) methods
OUTPUT:
DEMONSTRATE PRINTWRITER
import java.io.*; This is a string
-7
public class PrintWriterDemo { 4.5E-7
public static void main(String args[]) {
PrintWriter pw = new PrintWriter(System.out, true);
pw.println("This is a string");
int i = -7;
COURSE: OOPJ UNIT: 3 Pg. 32
READING AND WRITING FILES
Java provides a number of classes and methods that allow you to read and write
files
Two of the most often-used stream classes are FileInputStream and
FileOutputStream, which create byte streams linked to files.
To open a file, you simply create an object of one of these classes, specifying the
name of the file as an argument to the constructor.
EXAMPLE
class EnumExample1{
public enum Season { WINTER, SPRING, SUMMER, FALL }
OUTPUT:
public static void main(String[] args) { WINTER
SPRING
for (Season s : Season.values())
SUMMER
System.out.println(s); FALL
} }
Note: all enum constants are Public static
COURSE: OOPJ UNIT: 3 Pg. 39
// Use an enum to control a switch
// An enumeration of apple varieties.
enum Apple { statement.
Jonathan, GoldenDel, RedDel, switch(ap) {
Winesap, Cortland case Jonathan:
} System.out.println("Jonathan is
class EnumDemo { red.");
break;
public static void main(String args[])
{ case GoldenDel:
Apple ap; System.out.println("Golden
ap = Apple.RedDel;//static members Delicious is yellow.");
are access through class name break;
// Output an enum value. case RedDel:
System.out.println("Value of ap: " +System.out.println("Red Delicious is
ap); red.");
System.out.println(); break;
ap = Apple.GoldenDel; case Winesap:
// Compare two enum values. System.out.println("Winesap is
if(ap == Apple.GoldenDel) red.");
System.out.println("ap contains
OUTPUT: break;
ValueGoldenDel.\n");
of ap: RedDel case Cortland:
ap contains GoldenDel. System.out.println("Cortland is
red."); COURSE: OOPJ UNIT: 3 Pg. 40
THE VALUES( ) AND VALUEOF( ) METHODS