0% found this document useful (0 votes)
61 views13 pages

Exception Handling

The document outlines various Java programs demonstrating exception handling techniques, including try-catch-finally blocks and user-defined exceptions. It includes examples such as division operations, calculator functionalities, bank transactions, shopping cart management, and ATM simulations, each handling specific exceptions like division by zero, insufficient funds, and empty cart scenarios. Additionally, it provides practice questions for further exploration of exception handling in Java.

Uploaded by

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

Exception Handling

The document outlines various Java programs demonstrating exception handling techniques, including try-catch-finally blocks and user-defined exceptions. It includes examples such as division operations, calculator functionalities, bank transactions, shopping cart management, and ATM simulations, each handling specific exceptions like division by zero, insufficient funds, and empty cart scenarios. Additionally, it provides practice questions for further exploration of exception handling in Java.

Uploaded by

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

EXCEPTION HANDLING

1. Create a program that allows users to input two integers and performs
division. Use try-catch-finally to handle division by zero and always display
a closing message in finally.
Code:
import java.util.Scanner;

public class DivisionProgram {


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

try {
System.out.print("Enter the first integer: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second integer: ");
int num2 = scanner.nextInt();

int result = num1 / num2;


System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
} finally {
System.out.println("Program execution completed.");
}

scanner.close();
}
}

2. Develop a calculator program that catches input mismatches (e.g., entering


letters instead of numbers) using try-catch.
Code:
import java.util.Scanner;

public class CalculatorProgram {


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

try {
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();

System.out.print("Enter an operator (+, -, *, /): ");


char operator = scanner.next().charAt(0);

System.out.print("Enter the second number: ");


double num2 = scanner.nextDouble();

double result = 0;

switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 == 0) {
System.out.println("Error: Division by zero is not allowed.");
return;
}
result = num1 / num2;
break;
default:
System.out.println("Error: Invalid operator.");
return;
}

System.out.println("Result: " + result);

} catch (Exception e) {
System.out.println("Error: Invalid input. Please enter numeric
values.");
} finally {
System.out.println("Calculator program finished.");
}

scanner.close();
}
}

2. User-Defined Exceptions
1. Implement a program to simulate bank transactions. Throw a user-defined
exception if a withdrawal exceeds the account balance.
Code:
import java.util.Scanner;

// User-defined exception
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}

public class BankTransaction {


private double balance;

public BankTransaction(double initialBalance) {


this.balance = initialBalance;
}

public void withdraw(double amount) throws InsufficientFundsException {


if (amount > balance) {
throw new InsufficientFundsException("Withdrawal failed:
Insufficient balance.");
}
balance -= amount;
System.out.println("Withdrawal successful. Remaining balance: " +
balance);
}

public void deposit(double amount) {


balance += amount;
System.out.println("Deposit successful. Current balance: " + balance);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
BankTransaction account = new BankTransaction(1000); // Initial
balance

while (true) {
System.out.println("\n1. Deposit");
System.out.println("2. Withdraw");
System.out.println("3. Exit");
System.out.print("Choose an option: ");
int choice = scanner.nextInt();

try {
if (choice == 1) {
System.out.print("Enter deposit amount: ");
double amount = scanner.nextDouble();
account.deposit(amount);
} else if (choice == 2) {
System.out.print("Enter withdrawal amount: ");
double amount = scanner.nextDouble();
account.withdraw(amount);
} else if (choice == 3) {
System.out.println("Thank you for using our service.");
break;
} else {
System.out.println("Invalid choice. Please try again.");
}
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println("Error: Invalid input.");
scanner.next(); // Clear invalid input
}
}

scanner.close();
}
}

2. Write a program for an online shopping cart. Throw a user-defined exception


if the cart is empty during checkout.
Code:
import java.util.ArrayList;
import java.util.Scanner;

// User-defined exception
class EmptyCartException extends Exception {
public EmptyCartException(String message) {
super(message);
}
}

public class ShoppingCart {


private ArrayList<String> cart;

public ShoppingCart() {
cart = new ArrayList<>();
}

public void addItem(String item) {


cart.add(item);
System.out.println(item + " added to the cart.");
}

public void checkout() throws EmptyCartException {


if (cart.isEmpty()) {
throw new EmptyCartException("Checkout failed: Your cart is
empty.");
}
System.out.println("Proceeding to checkout. Items in cart:");
for (String item : cart) {
System.out.println("- " + item);
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
ShoppingCart shoppingCart = new ShoppingCart();

while (true) {
System.out.println("\n1. Add Item");
System.out.println("2. Checkout");
System.out.println("3. Exit");
System.out.print("Choose an option: ");
int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline

try {
if (choice == 1) {
System.out.print("Enter item to add: ");
String item = scanner.nextLine();
shoppingCart.addItem(item);
} else if (choice == 2) {
shoppingCart.checkout();
} else if (choice == 3) {
System.out.println("Thank you for shopping with us!");
break;
} else {
System.out.println("Invalid choice. Please try again.");
}
} catch (EmptyCartException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println("Error: Invalid input.");
}
}

scanner.close();
}
}

3. Develop a program to simulate an ATM machine. Throw a custom exception


if the user enters the wrong PIN more than three times.
Code:
import java.util.Scanner;

// User-defined exception
class WrongPinException extends Exception {
public WrongPinException(String message) {
super(message);
}
}

public class ATMMachine {


private static final String CORRECT_PIN = "1234"; // Predefined correct
PIN
private int attemptCount = 0;

public void validatePin(String enteredPin) throws WrongPinException {


if (!enteredPin.equals(CORRECT_PIN)) {
attemptCount++;
if (attemptCount >= 3) {
throw new WrongPinException("ATM access blocked: Too many
incorrect PIN attempts.");
}
throw new WrongPinException("Incorrect PIN. Try again.");
}
System.out.println("PIN validated successfully.");
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
ATMMachine atmMachine = new ATMMachine();

while (true) {
try {
System.out.print("Enter PIN: ");
String enteredPin = scanner.nextLine();
atmMachine.validatePin(enteredPin);
break; // Exit the loop if PIN is correct
} catch (WrongPinException e) {
System.out.println(e.getMessage());
if (atmMachine.attemptCount >= 3) {
System.out.println("Please contact customer service.");
break; // Exit the loop if the ATM is blocked
}
}
}

scanner.close();
}
}

1. try-catch-finally
1. Movie Ticket Booking: Write a program that takes the number of tickets a
user wants to book. Handle invalid inputs (e.g., entering negative numbers)
and ensure seat availability is always checked.
Code:
import java.util.Scanner;

public class MovieTicketBooking {


static final int TOTAL_SEATS = 100;
static int availableSeats = TOTAL_SEATS;

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.println("Welcome to Movie Ticket Booking!");


System.out.println("Total available seats: " + availableSeats);

while (true) {
try {
System.out.print("Enter the number of tickets you want to book: ");
int tickets = scanner.nextInt();

if (tickets <= 0) {
System.out.println("Invalid input. Please enter a positive
number.");
} else if (tickets > availableSeats) {
System.out.println("Not enough seats available. Please choose
fewer tickets.");
} else {
availableSeats -= tickets;
System.out.println("Successfully booked " + tickets + " tickets.");
System.out.println("Remaining seats: " + availableSeats);
break;
}
} catch (Exception e) {
System.out.println("Invalid input. Please enter a valid integer for
the number of tickets.");
scanner.nextLine(); // Clear the buffer
} finally {
// Can be used for any cleanup, though in this case it's not strictly
necessary
System.out.println("Attempt to book tickets completed.");
}
}
scanner.close();
}
}
2. Bank ATM Simulation: Develop an ATM program where users enter
withdrawal amounts. Handle invalid inputs (e.g., characters instead of
numbers) and insufficient funds.
3. Shopping Cart: Simulate a shopping cart system. Handle invalid product
IDs entered by users and display a final bill even if an exception occurs.
4. Number Guessing Game: Write a program for a guessing game where users
input numbers. Handle exceptions for invalid inputs and ensure the game
concludes gracefully in finally.
5. File Reader: Implement a program to read text from a file. Use try-catch-
finally to handle file-related exceptions and ensure the file stream is closed.
6. Exam Grading System: Create a program to accept student marks. Handle
invalid marks (e.g., greater than 100 or negative) using try-catch and ensure
the average is calculated.

2. User-Defined Exceptions
1. Hotel Booking System: Throw a custom exception if the user tries to book a
room when the hotel is fully occupied.
Code:
import java.util.Scanner;

class HotelFullException extends Exception {


public HotelFullException(String message) {
super(message);
}
}

public class HotelBookingSystem {


static final int TOTAL_ROOMS = 10;
static int availableRooms = TOTAL_ROOMS;

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.println("Welcome to the Hotel Booking System!");


System.out.println("Total available rooms: " + availableRooms);

while (true) {
try {
System.out.print("Enter the number of rooms you want to book: ");
int rooms = scanner.nextInt();

if (rooms <= 0) {
System.out.println("Invalid input. Please enter a positive
number.");
} else if (rooms > availableRooms) {
throw new HotelFullException("Sorry, the hotel is fully
occupied. No rooms available.");
} else {
availableRooms -= rooms;
System.out.println("Successfully booked " + rooms + "
room(s).");
System.out.println("Remaining rooms: " + availableRooms);
break;
}
} catch (HotelFullException e) {
System.out.println(e.getMessage());
break;
} catch (Exception e) {
System.out.println("Invalid input. Please enter a valid integer for
the number of rooms.");
scanner.nextLine(); // Clear the buffer
}
}
scanner.close();
}
}

Here are some more Java exception handling questions that can help you practice
and improve your skills:

### 1. **Divide by Zero Exception**


- Write a program that takes two integers as input from the user and divides the
first number by the second. Handle the `ArithmeticException` if the user attempts
to divide by zero and display a custom error message.

### 2. **File Not Found Exception**


- Write a program that attempts to open a file specified by the user. If the file
does not exist, throw a `FileNotFoundException` and display an appropriate
message.
### 3. **Array Index Out of Bounds Exception**
- Create a program that allows the user to input elements into an array. If the user
tries to access an index outside of the array's bounds, catch the
`ArrayIndexOutOfBoundsException` and print an error message.

### 4. **Number Format Exception**


- Write a program that reads a number input as a string and converts it to an
integer. If the string cannot be converted to an integer, handle the
`NumberFormatException` and display a message like "Invalid input, please enter
a valid number."

### 5. **Null Pointer Exception**


- Create a program where the user inputs a string, and the program attempts to
display the length of the string. If the user enters a `null` value, catch the
`NullPointerException` and display a custom message explaining that the input
cannot be `null`.

### 6. **Custom Exception for Invalid Age**


- Write a program that asks the user for their age and throws a custom exception
(`InvalidAgeException`) if the age entered is below 0 or greater than 130. Display
an appropriate message when the exception is thrown.

### 7. **Multiple Exceptions Handling**


- Create a program where the user inputs two numbers and performs operations
like addition, subtraction, multiplication, and division. Handle multiple exceptions,
including `ArithmeticException`, `InputMismatchException`, and
`NumberFormatException`.

### 8. **Invalid Input for Date Format**


- Write a program that asks the user to enter a date in the format "yyyy-MM-dd".
If the input doesn't match the expected format, handle the exception and inform the
user of the correct format to use.

### 9. **Invalid Bank Withdrawal**


- Write a program for a bank account system where a user can withdraw money.
If the user tries to withdraw more money than their balance, throw a custom
exception (`InsufficientBalanceException`) and display a message that the
withdrawal cannot be processed.

### 10. **Invalid Temperature Conversion**


- Create a program that converts temperatures between Celsius and Fahrenheit. If
the user inputs a temperature value that is below absolute zero (in either scale),
throw a custom exception (`InvalidTemperatureException`) and explain why the
input is invalid.

### 11. **String Format Exception in URL Validation**


- Write a program that validates a URL. If the URL doesn't follow the correct
format (e.g., missing "http://"), throw a custom exception (`InvalidURLException`)
and display an appropriate message.

### 12. **Exponential Overflow Exception**


- Create a program that computes the exponential value of a number (e.g., `x^y`).
If the result exceeds the range of the data type, catch the overflow exception and
display a message explaining the overflow occurred.

These questions can help you explore a variety of exception handling scenarios,
from built-in exceptions to custom ones, and improve your understanding of error
management in Java.

You might also like