UNIT –IV
I. TYPES OF ERRORS
Compile Time Errors – Errors detected and displayed by java compiler.
Compiler will not create .class file.
The most common errors are:
Missing semicolons.
Missing brackets in classes and methods.
Misspelling keywords.
Missing double quotes in strings.
Use of undeclared variables.
Incompatible types in assignments.
Run Time Errors – Program compiles successfully creating .class file but may not run
properly.
Such programs produce wrong results due to wrong logic or may terminate due to
errors.
The common run time errors are:
Dividing an integer by zero.
Array out of bounds.
Trying to store a value into an array of an incompatible class or type.
Passing a parameter that is not in a valid range.
Illegally change the status of thread.
Converting invalid string to number.
Example:
int a = 10, b = 5, c = 5;
int x = a/ (b-c); //Division by zero
Arithmetic Exception
II. EXCEPTIONS – Condition caused by a run time error.
When java interpreter encounters an error, it creates an exception object and throws it.
Then, catch the exception and display error message.
Tasks to be performed:
i. Find the problem (Hit the exception).
ii. Inform error occurred (Throw the exception).
1
iii. Receive error information (Catch the exception).
iv. Take actions (Handle the exception).
Common Java Exceptions:
i. Arithmetic Exception – Division by zero.
ii. Array Index of Bounds Exception – Bad array indexes.
iii. Array Store Exception – Store wrong data type into an array.
iv. File Not Found Exception – Attempt to access a non-existent file.
v. IO Exception – General I/O failures. Inability to read from a file.
vi. Null Pointer Exception – Referencing a null object.
vii. Number Format Exception – Caused when a conversion between string and number fails.
viii. Out of Memory Exception – When there is not enough memory for new objects.
ix. Security Exception – When applet tries to perform an action not allowed by browser
security settings
x. Stack Overflow Exception – System runs out of stack space.
xi. String Out of Bounds Exception – Program attempts to access non-existent character
position in a string.
Categories of Exceptions:
Two Types
i. Checked Exceptions: These exceptions are explicitly handled in the code itself with the
help of try-catch blocks. They are extended from java.lang.Exception class.
ii. Unchecked Exceptions: JVM handles such exceptions. They are extended from
java.lang.RuntimeException class.
Syntax of Exception Handling Code:
Exception handling - Throwing an exception and catching it.
TRY BLOCK
Causes an Exception
Throws
Exception
CATCH BLOCK
Handles an Exception
2
Try Block:
Keyword 'try' preface a block of code that cause an error and throws exception.
Try block can have one or more statements.
Every 'try' should be followed at least by one 'catch' statement.
If anyone generates exception remaining statement skipped and execution jumps to 'catch'
block.
Catch Block:
The ‘catch’ block catches the exception thrown and handles it appropriately.
The catch statement is passed a single parameter which is reference to exception object, then
exception caught and statements in catch block executed.
Exception not caught default exception handler will terminate execution.
Example:
class exception
{
public static void main(String args[ ])
{
try
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
int c=a/b;
System.out.println(c);
}
catch(Exception d)
{
System.out.println(d);
}
}
}
Output:
D:/java>java exception 10 0
java.lang.ArithmeticException /by zero
3
Multiple Catch Statements:
General form:
try
{
Statement;
}
Catch (Exception-Type-1 e)
{
Statement;
}
catch(Exception-Type-2 e)
{
Statement;
}
.
.
catch(Exception-Type-N e)
{
Statement;
}
There can be more than one catch statements in java. When an exception in try block
generated, the first statement whose parameter matches with the exception object will be
executed, and remaining statements skipped.
Finally Statements: try
General form: {.......}
try catch( )
{......} {.......}
finally catch( )
{......} {.......}
.
.
finally
{.......}
4
The finally statement is used to handle an exception that is not caught by any previous catch
statements.
It is added immediately after try or after last catch block.
III. STREAM CLASSES
Stream classes categorized into two groups:
i. Byte Stream Classes.
ii. Character Stream Classes.
Java Stream Classes
Byte Stream Character Stream
Input Stream Output Stream Reader Writer
Memory File Pipe Memory File Pipe
BYTE STREAM CLASSES:
Byte stream classes supports handling IO operations on bytes.
Java provides two byte stream classes:
i. Input stream classes
ii. Output stream classes.
Input Stream Classes - Super class Input Stream; cannot create instances, it is an abstract
class.
Object
INPUT STREAM
File Input Stream
Sequence Input Stream
Pipe Input Stream
Object Input Stream
5
Byte Array Input Stream
String Buffer Input Stream
Filter Input Stream
Buffered Input Stream
Pushback Input Stream
Data Input Stream
Data Input(Interface)
Methods
readShort( )
readInt( )
readLong( )
readFloat( )
readDouble( )
readLline( )
readChar( )
readBoolean( )
Input Stream Methods
1. read( ) – Reads a byte.
2. read(byte[ ]) – Reads an array of byte into b.
3. read(byte b[ ], int n, int m) – Reads m bytes into b starting from nth byte.
4. available( ) – Gives number of bytes available in input.
5. skip( ) – Skips over n byte.
6. reset( ) – Goes back to beginning of stream.
7. close( ) – Closes the input stream.
OUTPUT STREAM – Super Class OUTPUT STREAM; Abstract class, cannot be
instantiated.
Object
Output Stream
File Output Stream
Object Output Stream
Piped Output Stream
Byte Array Output Stream
6
Filter Output Stream
Buffered Output Stream
Pushback Output Stream
Data Output Stream
Data Output (Interface)
Methods
WriteShort( )
WriteInt( )
WriteLong( )
WriteFloat( )
WriteDouble( )
WriteBoolean( )
WriteByte( )
WriteChar( )
Output Stream Methods
1. Write( ) – writes a byte to output stream
2. Write(byte b[ ]) – writes all bytes in b to output stream.
3. Write(byte b[ ], int n, int m) – writes m bytes from array b starting from nth byte.
4. close( ) – closes output stream.
5. flush( ) – flushes output stream.
CHARACTER STREAM CLASSES
Character stream classes supports managing IO operations on characters.
Two kinds of character stream classes.
Reader Stream Classes.
Writer Stream Classes.
Reader Stream Classes – Read characters from files
Object
Reader
Buffered Reader
String Reader
7
Char Array Reader
Pipe Reader
Input Stream Reader
File Reader
Filter Reader
Pushback Reader
Writer Stream Reader – Performs output operation on files.
Object
Writer
Buffered Writer
String Writer
Char Array Writer
Pipe Writer
Output Stream Writer
File Writer
Filter Writer
Stream Classes for IO Operations:
Source / Characters Bytes
Destination Read Write Read Write
Char Array Char Array Byte Array Input Byte Array Output
Memory
Reader Writer Stream Stream
File File Reader File Writer File Input Stream File Output Stream
Pipe Piped Reader Piped Writer Piped Input Stream Piped Output Stream
Reader / Writing Characters:
// Copying characters from one file to another.
import java.io.*;
class filecopy
{
8
public static void main(String args[])throwsIOException
{
try
{
DataInputStream din=new DataInputStream(System.in);
String sfile,dfile;
int n=0;
System.out.println("FileCopy");
System.out.println("Enter the Source File");
sfile=din.readLine();
System.out.println(sfile);
System.out.println("Enter the Destination File");
dfile=din.readLine();
System.out.println(dfile);
FileReader fr=new FileReader(sfile);
FileWriter fw=new FileWriter(dfile);
while((n= fr.read())!=-1)
{
fw.write(n);
}
System.out.println("File Copied");
fr.close();
fw.close();
}
catch(Exception e)
{
System.out.println("File not Found");
}
}
}
---------