[go: up one dir, main page]

0% found this document useful (0 votes)
14 views7 pages

Exception Handling

The document provides various Java programming scenarios demonstrating exception handling, including checked and unchecked exceptions. It covers file handling, array index issues, number format errors, null pointer exceptions, and custom exceptions for age validation and user registration. Each scenario includes code examples illustrating the use of try-catch blocks, finally statements, and custom exception classes.

Uploaded by

01fe23bca218
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)
14 views7 pages

Exception Handling

The document provides various Java programming scenarios demonstrating exception handling, including checked and unchecked exceptions. It covers file handling, array index issues, number format errors, null pointer exceptions, and custom exceptions for age validation and user registration. Each scenario includes code examples illustrating the use of try-catch blocks, finally statements, and custom exception classes.

Uploaded by

01fe23bca218
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
You are on page 1/ 7

1.

File Handling Scenario (checked exception)


import java.io.*;

public class ReadFileExample {


public static void main(String[] args) {
try {
FileReader fr = new FileReader("nonexistent.txt");
BufferedReader br = new BufferedReader(fr);
System.out.println(br.readLine());
} catch (FileNotFoundException e) {
System.out.println("File not found. Please check the file path.");
} catch (IOException e) {
System.out.println("Error reading the file.");
}
}
}

2.Array Index Out of Bounds(unchecked exception)

public class ArrayExample {


public static void main(String[] args) {
int[] arr = {1, 2, 3};

try {
System.out.println(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid array index accessed.");
}
}
}

3.Number Format Exception(unchecked exception)


public class NumberFormatExample {
public static void main(String[] args) {
String input = "abc";

try {
int num = Integer.parseInt(input);
System.out.println("Number: " + num);
} catch (NumberFormatException e) {
System.out.println("Invalid number format.");
}
}
}

4. Null Pointer Exception(unchecked exception)


public class NullPointerExample {
public static void main(String[] args) {
String str = null;

try {
System.out.println(str.length());
} catch (NullPointerException e) {
System.out.println("Cannot access method on a null object.");
}
}
}

Scenario: Handling Different Exceptions in a Single Program (try with multiple catch)

public class MultiCatchExample {


public static void main(String[] args) {
String str = null;
int[] arr = {10, 20, 30};

try {
// This line will throw a NullPointerException
System.out.println("String length: " + str.length());

// This line would throw ArrayIndexOutOfBoundsException (if reached)


System.out.println("Array element: " + arr[5]);

} catch (NullPointerException e) {
System.out.println("Caught NullPointerException: String is null.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: Invalid array index.");
} catch (Exception e) {
System.out.println("Caught General Exception: " + e.getMessage());
}

System.out.println("Program continues...");
}
}

Scenario: Closing a Resource (like a database or file connection)


public class FinallyExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
System.out.println("Result: " + result);
} finally {
System.out.println("This block always executes, even if there is an exception.");
}

// This line won't be reached unless exception is handled


System.out.println("Program continues...");
}
}

Scenario: Reading a Number and Handling Input Errors


import java.util.Scanner;

public class TryCatchFinallyExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

try {
System.out.print("Enter a number: ");
int number = Integer.parseInt(scanner.nextLine());
System.out.println("You entered: " + number);
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid number.");
} finally {
scanner.close();
System.out.println("Scanner closed. This block always runs.");
}

System.out.println("Program continues...");
}
}
Scenario: Validate Age for Voting using Throw
public class ThrowExample {
public static void checkAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or older to vote.");
} else {
System.out.println("You are eligible to vote.");
}
}

public static void main(String[] args) {


try {
checkAge(15); // Will throw exception
} catch (IllegalArgumentException e) {
System.out.println("Caught Exception: " + e.getMessage());
} finally {
System.out.println("Age validation completed.");
}

System.out.println("Program continues...");
}
}

Scenario: File Reading with Checked Exception


import java.io.*;

public class ThrowsExample {

// Method declares it may throw IOException


public static void readFile(String fileName) throws IOException {
FileReader file = new FileReader(fileName);
BufferedReader br = new BufferedReader(file);
System.out.println("File content: " + br.readLine());
br.close();
}

public static void main(String[] args) {


try {
readFile("example.txt"); // You can create this file to test
} catch (IOException e) {
System.out.println("Caught IOException: " + e.getMessage());
} finally {
System.out.println("File read attempt completed.");
}
}
}

Scenario: Custom Exception for Invalid Age


1. Define the Custom Exception:
// Custom exception class
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
2. Use the Custom Exception in Your Code:
public class CustomExceptionExample {

// Method that throws the custom exception


public static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or older.");
} else {
System.out.println("Valid age for registration.");
}
}

public static void main(String[] args) {


try {
validateAge(16); // Will throw custom exception
} catch (InvalidAgeException e) {
System.out.println("Caught custom exception: " + e.getMessage());
} finally {
System.out.println("Age validation check complete.");
}
}
}

Scenario: Bank Withdrawal with Custom Checked Exception


1. Create a Custom Checked Exception
// Custom checked exception
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
2. Use the Custom Exception in Business Logic
public class BankAccount {
private int balance = 5000;

// Method that declares it may throw the custom checked exception


public void withdraw(int amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("Withdrawal amount exceeds available
balance.");
} else {
balance -= amount;
System.out.println("Withdrawal successful. Remaining balance: " + balance);
}
}

public static void main(String[] args) {


BankAccount account = new BankAccount();

try {
account.withdraw(6000); // This will trigger the exception
} catch (InsufficientFundsException e) {
System.out.println("Exception caught: " + e.getMessage());
} finally {
System.out.println("Transaction attempt finished.");
}
}
}

Scenario: User Registration with Custom Unchecked Exception

1. Create a Custom Unchecked Exception


// Custom unchecked exception
class InvalidUsernameException extends RuntimeException {
public InvalidUsernameException(String message) {
super(message);
}
}
2. Use the Custom Exception in Logic
public class UserRegistration {

public void registerUser(String username) {


if (username == null || username.length() < 5) {
throw new InvalidUsernameException("Username must be at least 5 characters long.");
} else {
System.out.println("User registered successfully: " + username);
}
}

public static void main(String[] args) {


UserRegistration reg = new UserRegistration();

try {
reg.registerUser("abc"); // Will throw custom unchecked exception
} catch (InvalidUsernameException e) {
System.out.println("Exception caught: " + e.getMessage());
} finally {
System.out.println("Registration attempt complete.");
}
}
}

You might also like