Java Exception Handling - Practice Exercises with Solutions
Exercise 1: Divide Two Numbers
------------------------------
Code:
import [Link];
public class DivideNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter numerator: ");
int a = [Link]();
[Link]("Enter denominator: ");
int b = [Link]();
try {
[Link]("Result: " + (a / b));
} catch (ArithmeticException e) {
[Link]("Error: Cannot divide by zero");
}
}
}
Output:
Enter numerator:
10
Enter denominator:
0
Error: Cannot divide by zero
Exercise 2: Handle String to Integer Conversion Error
-----------------------------------------------------
Code:
import [Link];
public class StringToInt {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
String input = [Link]();
try {
int num = [Link](input);
[Link]("You entered: " + num);
} catch (NumberFormatException e) {
[Link]("Invalid number format!");
}
}
}
Output:
Enter a number:
abc
Invalid number format!
Exercise 3: Array Out of Bounds
-------------------------------
Code:
public class ArrayExample {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
try {
[Link](arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Error: Array index is out of bounds!");
}
}
}
Output:
Error: Array index is out of bounds!
Exercise 4: Voting Age with throw & throws
------------------------------------------
Code:
public class Voting {
static void checkVotingEligibility(int age) throws ArithmeticException {
if (age < 18) {
throw new ArithmeticException("Not eligible for voting");
} else {
[Link]("Eligible for voting");
}
}
public static void main(String[] args) {
checkVotingEligibility(16);
}
}
Output:
Exception in thread "main" [Link]: Not eligible for voting
Exercise 5: Multiple Exceptions
-------------------------------
Code:
import [Link];
public class MultipleExceptions {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Choose:
1. Divide by zero
2. Array index error");
int choice = [Link]();
try {
if (choice == 1) {
int a = 5 / 0;
} else if (choice == 2) {
int[] arr = {1, 2, 3};
[Link](arr[5]);
}
} catch (ArithmeticException e) {
[Link]("Arithmetic Exception occurred");
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array Index Exception occurred");
}
}
}
Output:
Choose:
1. Divide by zero
2. Array index error
1
Arithmetic Exception occurred