Core_java_unit_IV

unit3

File and Exception Handling

Exception

Exceptions in Java are events that disrupt the normal flow of the program's instructions. They are used to handle errors and other exceptional events, allowing a program to continue running even if an unexpected situation occurs.

4.1 Exception and Error

Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked exception. However, according to Oracle, there are three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error

Difference between Checked and Unchecked Exceptions

1) Checked Exception

The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

Error

Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError etc.

4.2 Use of try, catch, throw, throws and finally

Keyword Description
Try The "try" keyword is used to specify a block where we should place an exception code. It means we can't use the try block alone. The try block must be followed by either catch or finally.
Catch The "catch" block is used to handle the exception. It must be preceded by a try block which means we can't use the catch block alone. It can be followed by a finally block later.
Finally The "finally" block is used to execute the necessary code of the program. It is executed whether an exception is handled or not.
Throw The "throw" keyword is used to throw an exception.
Throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn't throw an exception. It is always used with the method signature.

4.3 Built in Exception

Java provides a comprehensive set of built-in exceptions that cover a wide range of common error conditions. These exceptions are part of the Java standard library and are organized in a well-defined hierarchy, with Throwable at the top, followed by Exception and Error.

  • 1. Throwable
    • o Error
      • • Examples: OutOfMemoryError, StackOverflowError, VirtualMachineError
    • o Exception
      • RuntimeException
        • • Examples: NullPointerException, IndexOutOfBoundsException, ArithmeticException
      • Checked Exceptions
        • • Examples: IOException, SQLException, FileNotFoundException

Common Built-in Exceptions

1. ArithmeticException

This exception is thrown when an illegal arithmetic operation is performed, such as division by zero.

Example

public class ArithmeticExceptionExample {
public static void main(String[] args) {
try { int result = 10 / 0; }
catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: " + e.getMessage());
}
}}

Output:

ArithmeticException caught: / by zero

2. NullPointerException

This exception is thrown when trying to use a null object reference as if it were a valid object.

Example

public class NullPointerExceptionExample {
public static void main(String[] args) {
try {
String str = null;
System.out.println(str.length());
}
catch (NullPointerException e) {
System.out.println("NullPointerException caught: " + e.getMessage());
}
}
}

Output:

NullPointerException caught: Cannot invoke "String.length()" because "str" is null

3. ArrayIndexOutOfBoundsException

This exception is thrown when trying to access an array element with an illegal index.

Example

public class ArrayIndexOutOfBoundsExceptionExample {
public static void main(String[] args) {
try {
int[] arr = new int[5];
int value = arr[10]; // This will throw an exception
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException caught: " + e.getMessage());
}
}
}

Output:

ArrayIndexOutOfBoundsException caught: Index 10 out of bounds for length 5

4. IOException

This exception is thrown when an I/O operation fails or is interrupted.

Example

import java.io.*;
public class IOExceptionExample {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("nonexistentfile.txt");
}
catch (IOException e) {
System.out.println("IOException caught: " + e.getMessage());
}
}
}

Output:

IOException caught: nonexistentfile.txt (No such file or directory)

5. FileNotFoundException

This exception is a subclass of IOException and is thrown when an attempt to open the file denoted by a specified pathname has failed.

Example

import java.io.*;
public class FileNotFoundExceptionExample {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("nonexistentfile.txt");
}
catch (FileNotFoundException e) {
System.out.println("FileNotFoundException caught: " + e.getMessage());
}
}
}

Output:

IOException caught: nonexistentfile.txt (No such file or directory)

6. ClassNotFoundException

This exception is thrown when an application tries to load a class through its string name but no definition for the class with the specified name could be found.

Example

public class ClassNotFoundExceptionExample {
public static void main(String[] args) {
try {
Class.forName("com.nonexistent.Class");
}
catch (ClassNotFoundException e) {
System.out.println("ClassNotFoundException caught: " + e.getMessage());
}
}
}

Output:

ClassNotFoundException caught: com.nonexistent.Class

7. NumberFormatException

This exception is thrown when an attempt to convert a string to a numeric type fails because the string does not have the appropriate format.

Example

public class NumberFormatExceptionExample {
public static void main(String[] args) {
try {
int number = Integer.parseInt("invalid number");
}
catch (NumberFormatException e) {
System.out.println("NumberFormatException caught: " + e.getMessage());
}
}
}

Output:

NumberFormatException caught: For input string: "invalid number"

4.4 Custom Exceptions in Java

Custom exceptions in Java allow you to create specific error conditions that are more meaningful to your application. By creating your own exceptions, you can provide better context and handling for the errors that your application might encounter.

Steps to Create a Custom Exception

1. Define the Exception Class: Extend Exception for a checked exception or RuntimeException for an unchecked exception.
2. Provide Constructors: Implement constructors to initialize the exception with appropriate messages and causes.
3. Throw the Custom Exception: Use the throw keyword to throw your custom exception when a specific condition occurs.
4. Catch the Custom Exception: Use a try-catch block to handle the custom exception where necessary.

Example of a Custom Checked Exception

Define the Exception Class: public class InvalidAgeException extends Exception {
// Default constructor
public InvalidAgeException() {
super("Invalid age provided.");
}

// Constructor that accepts a custom message
public InvalidAgeException(String message) {
super(message);
}

// Constructor that accepts a custom message and a cause
public InvalidAgeException(String message, Throwable cause){
super(message, cause);
}
}

Use the Custom Exception:

public class CustomExceptionExample {
// Method that throws the custom exception
public static void checkAge(int age) throws InvalidAgeException {
if (age < 0 || age > 150) {
throw new InvalidAgeException("Age must be between 0 and 150. Provided age: " + age);
} else {
System.out.println("Valid age: " + age);
}
}
public static void main(String[] args) {
try {
checkAge(200); // This will throw the custom exception
}
catch (InvalidAgeException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}

Output:

Exception caught: Age must be between 0 and 150. Provided age: 200

Example of a Custom Unchecked Exception

Define the Exception Class:

public class NegativeNumberException extends RuntimeException {
// Default constructor
public NegativeNumberException() {
super("Negative number provided.");
}
// Constructor that accepts a custom message
public NegativeNumberException(String message) {
super(message);
}
// Constructor that accepts a custom message and a cause
public NegativeNumberException(String message, Throwable cause) {
super(message, cause);
}
}

the Custom Exception:

public class UncheckedCustomExceptionExample {
// Method that throws the custom unchecked exception
public static int factorial(int number) {
if (number < 0) {
throw new NegativeNumberException("Factorial is not defined for negative numbers. Provided number: " + number);
}
int result = 1;
for (int i = 1; i <= number; i++) {
result *= i;
}
return result;
}
public static void main(String[] args) {
try {
System.out.println(factorial(-5)); // This will throw the custom exception
}
catch (NegativeNumberException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}

Output:

Exception caught: Factorial is not defined for negative numbers. Provided number: -5

Best Practices for Custom Exceptions

1. Use Meaningful Names: Name your exception classes clearly to indicate the type of error.
2. Provide Multiple Constructors: Include constructors that accept messages and causes to provide more information about the exception.
3. Documentation: Document your custom exceptions so that other developers understand when and why they should be used.
4. Avoid Overuse: Use custom exceptions meanly and only when the standard exceptions are not sufficient.

4.5 Throwable Class

The Throwable class in Java is the superclass of all errors and exceptions in the Java language. It is part of the java.lang package and serves as the base class for all objects that can be thrown using the throw statement.
Throwable provides several constructors:
• Throwable(): Constructs a new throwable with null as its detail message.
• Throwable(String message): Constructs a new throwable with the specified detail message.
• Throwable(String message, Throwable cause): Constructs a new throwable with the specified detail message and cause.

Methods

Some important methods in Throwable include:
• String getMessage(): Returns the detail message string of this throwable.
• String getLocalizedMessage(): Creates a localized description of this throwable.
• Throwable getCause(): Returns the cause of this throwable or null if the cause is nonexistent or unknown.
• Throwable initCause(Throwable cause): Initializes the cause of this throwable.
• String toString(): Returns a short description of this throwable.
• void printStackTrace(): Prints this throwable and its backtrace to the standard error stream.

Example:

public class ThrowableExample {
public static void main(String[] args) {
try {
throw new Exception("This is an exception");
}
catch (Exception e) {
System.out.println("Caught an exception:");
System.out.println("Message: " + e.getMessage());
System.out.println("Cause: " + e.getCause());
System.out.println("Stack Trace:");
e.printStackTrace();
}
}
}

File Handling

File handling in Java is essential for performing operations such as reading, writing, and manipulating files and directories. Java provides several classes and methods in the java.io and java.nio.file packages to facilitate file handling.

Using java.io Package

File Class

The java.io.File class is used to represent file and directory pathnames in an abstract manner.

Key Methods

• boolean createNewFile(): Creates a new empty file if it does not exist.
• boolean delete(): Deletes the file or directory.
• boolean exists(): Tests whether the file or directory exists.
• String getName(): Returns the name of the file or directory.
• String getAbsolutePath(): Returns the absolute pathname string.
• boolean isDirectory(): Tests whether the file is a directory.
• boolean isFile(): Tests whether the file is a regular file.
• String[] list(): Returns an array of strings naming the files and directories in the directory.
• long length(): Returns the length of the file.

4.6 Overview of Different Stream (Byte Stream, Character stream)

In Java, file I/O can be performed using either byte streams or character streams, depending on the nature of the data being handled. Byte streams are used for handling raw binary data, while character streams are used for handling character data, which involves text files.

Byte Streams

Byte streams handle I/O of raw binary data. They use InputStream and OutputStream as the base classes.

Key Byte Stream Classes

• FileInputStream: Reads raw bytes from a file.
• FileOutputStream: Writes raw bytes to a file.

Character Streams

Character streams handle I/O of character data. They use Reader and Writer as the base classes.

Key Character Stream Classes

• FileReader: Reads characters from a file.
• FileWriter: Writes characters to a file.
• BufferedReader: Buffers characters for efficient reading.
• BufferedWriter: Buffers characters for efficient writing.

4.7 Readers and Writers class

In Java, the Reader and Writer classes are the abstract superclasses for all classes that handle reading and writing character streams, respectively. They are part of the java.io package.

Readers

Key Reader Subclasses
• FileReader: Reads characters from files.
• BufferedReader: Buffers input for efficient reading of characters, arrays, and lines.
• InputStreamReader: Bridges byte streams to character streams, translating bytes to characters using a specified charset.
• StringReader: Reads characters from strings.
Key Methods
• int read(): Reads a single character.
• int read(char[] cbuf, int offset, int length): Reads characters into a portion of an array.
• boolean ready(): Tells whether the stream is ready to be read.
• void close(): Closes the stream and releases any system resources associated with it.

Example Usage

FileReader and BufferedReader

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReaderExample {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Writers

Key Writer Subclasses

• FileWriter: Writes characters to files.
• BufferedWriter: Buffers output for efficient writing of characters, arrays, and strings.
• OutputStreamWriter: Bridges character streams to byte streams, encoding characters to bytes using a specified charset.
• StringWriter: Writes characters to a string buffer.

Key Methods

• void write(int c): Writes a single character.
• void write(char[] cbuf, int offset, int length): Writes a portion of an array of characters.
• void write(String str, int offset, int length): Writes a portion of a string.
• void flush(): Flushes the stream.
• void close(): Closes the stream and releases any system resources associated with it.

Example

FileWriter and BufferedWriter


import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class WriterExample {
public static void main(String[] args) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt"))) {
writer.write("Hello, World!");
writer.newLine();
writer.write("This is a BufferedWriter example.");
}
catch (IOException e) {
e.printStackTrace();
}
}
}

4.11 FileReader and FileWriter class

The FileReader and FileWriter classes in Java are part of the java.io package and are used for reading and writing text files, respectively. They are designed for character-based input and output.

FileReader Class

The FileReader class is a convenience class for reading character files. It inherits from InputStreamReader and provides functionality to read data from files.

Key Methods

• int read(): Reads a single character.
• int read(char[] cbuf, int offset, int length): Reads characters into a portion of an array.
• void close(): Closes the stream and releases any system resources associated with it.

Example Usage

import java.io.FileReader;
import java.io.IOException;

public class FileReaderExample {
public static void main(String[] args) {
try (FileReader reader = new FileReader("example.txt")) {
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}

FileWriter Class

The FileWriter class is a convenience class for writing character files. It inherits from OutputStreamWriter and provides functionality to write data to files.

Key Methods

• void write(int c): Writes a single character.
• void write(char[] cbuf, int offset, int length): Writes a portion of an array of characters.
• void write(String str, int offset, int length): Writes a portion of a string.
• void flush(): Flushes the stream.
• void close(): Closes the stream and releases any system resources associated with it.

Example Usage

import java.io.FileWriter;
import java.io.IOException;

public class FileWriterExample {
public static void main(String[] args) {
try (FileWriter writer = new FileWriter("example.txt")) {
writer.write("Hello, World!");
writer.write("\nThis is a FileWriter example.");
}
catch (IOException e) {
e.printStackTrace();
}
}
}

4.12 Buffered Reader class

These classes are used for reading and writing text files efficiently.

Example Usage

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedReaderWriterExample {
public static void main(String[] args) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt"))) {
writer.write("Hello, World!");
}
catch (IOException e) {
e.printStackTrace();
}

try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}

No comments:

Post a Comment