0% found this document useful (0 votes)
18 views9 pages

Java Error and Exception Handling Guide

Uploaded by

kesavanram07
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views9 pages

Java Error and Exception Handling Guide

Uploaded by

kesavanram07
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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 [Link] class.
ii. Unchecked Exceptions: JVM handles such exceptions. They are extended from
[Link] 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=[Link](args[0]);
int b=[Link](args[1]);
int c=a/b;
[Link](c);
}
catch(Exception d)
{
[Link](d);
}
}
}

Output:
D:/java>java exception 10 0
[Link] /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 [Link].*;
class filecopy
{

8
public static void main(String args[])throwsIOException
{
try
{
DataInputStream din=new DataInputStream([Link]);
String sfile,dfile;
int n=0;
[Link]("FileCopy");
[Link]("Enter the Source File");
sfile=[Link]();
[Link](sfile);
[Link]("Enter the Destination File");
dfile=[Link]();
[Link](dfile);
FileReader fr=new FileReader(sfile);
FileWriter fw=new FileWriter(dfile);
while((n= [Link]())!=-1)
{
[Link](n);
}
[Link]("File Copied");
[Link]();
[Link]();
}
catch(Exception e)
{
[Link]("File not Found");
}
}
}

---------

Common questions

Powered by AI

Java handles exceptions by creating an exception object whenever an error occurs and throwing it. The try block is used to enclose code that might generate an exception. If an exception occurs, the program control passes to the corresponding catch block, which catches and handles the exception. Inside the catch block, a reference to the exception object allows for handling the specific error. The finally block, which executes after the try and catch blocks, regardless of whether an exception occurred, is used for cleanup activities such as closing resources .

Byte stream classes in Java are used for handling input and output operations on bytes, represented by classes like FileInputStream and FileOutputStream. They provide methods to read and write data byte by byte, primarily used for binary data like images or executable files. Character stream classes, such as FileReader and FileWriter, operate on characters, enabling input and output operations in character-oriented (textual) data, automatically handling character encoding. While byte streams are suitable for all types of data, character streams simplify dealing with text by considering character encodings .

Compile-time errors occur when the Java compiler finds syntactical issues in the code, such as missing semicolons, brackets, or misspelled keywords, preventing the generation of the .class file. These errors must be resolved before the program proceeds to runtime. In contrast, runtime errors occur when a program, which has successfully compiled, encounters issues during execution, such as division by zero or accessing array elements out of bounds. These errors may cause the program to produce incorrect results or terminate unexpectedly .

The DataInput interface provides several methods such as readShort(), readInt(), and readBoolean() that facilitate reading binary data or primitives from an input stream in a machine-independent way. These methods are significant as they help in interpreting raw byte streams as meaningful data types, ensuring the correct decoding of data stored or transmitted in a binary format. This is particularly crucial in applications that require precise data handling, such as file parsing, network communication, and dealing with data serialization and deserialization .

Finally blocks are particularly useful in scenarios where resources need to be released or closed, such as file streams or database connections, ensuring that cleanup code is executed regardless of whether an exception occurred. This prevents resource leaks and ensures the program does not hold onto memory or system files indefinitively. A potential pitfall they help avoid is neglecting resource cleanup in the event of an exception, which could lead to memory leaks or locked resources, thereby stabilizing the application's performance and reliability .

Multiple catch statements allow a program to handle different exceptions separately by specifying various catch blocks following a single try block. The exception handling mechanism in Java tests catch blocks in the order they appear and executes the first block that matches the thrown exception's type. It is crucial that the catch block for the most specific type of exception is placed before the one for a more general type, because once a catch block is executed, subsequent ones are skipped, making it impossible to catch more specific exceptions if handled after more general ones .

Checked exceptions are exceptions that must be explicitly handled in the code, typically using try-catch blocks. They derive from the java.lang.Exception class and the compiler checks them at compile time. Unchecked exceptions, on the other hand, derive from java.lang.RuntimeException class, are not required to be caught or declared, and are typically due to programming bugs, such as logic errors. The distinction necessitates that developers write more verbose and cautious code when dealing with checked exceptions to ensure that all potential failures are appropriately handled .

Challenges arise when catch blocks are ordered incorrectly concerning the exception hierarchy. Placing a catch block for a general exception class before a specific one causes all matching exceptions to be caught by the general handler, preventing the specific handler from executing. This not only results in improper exception handling but also obscures the actual exception details, complicating debugging. To avoid these issues, developers should order catch blocks from the most specific to the most general, ensuring that all exceptions are handled precisely as intended .

ArithmeticException and NullPointerException exemplify logic errors that runtime exceptions capture. An ArithmeticException typically occurs when an arithmetic operation is deemed invalid, such as dividing by zero, indicating flawed logic where safer checks might have been overlooked. NullPointerException arises when the application tries to use an object reference that has not been initialized, indicating missing checks or erroneous logic assumptions about object availability or state. Both are symptomatic of runtime exceptions where logical oversights or improper handling could lead to application failures at runtime, demanding careful debugging and logic refinement .

BufferedReader and BufferedWriter are part of Java's character stream classes designed to optimize IO operations by reducing disk access overhead. BufferedReader, which wraps around a Reader, improves reading efficiency by buffering characters, arrays, or lines, making it faster to read text data. BufferedWriter, wrapping around a Writer, does the same for writing operations, allowing characters to be buffered before output to a stream. Their use minimizes the number of actual read/write operations performed on the underlying IO stream, enhancing performance in applications involving large data processing or frequent IO operations .

You might also like