-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExceptionHandlingExample.java
More file actions
29 lines (25 loc) · 1.04 KB
/
ExceptionHandlingExample.java
File metadata and controls
29 lines (25 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.util.Scanner;
public class ExceptionHandlingExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
// Code that might throw an exception
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
int result = num1 / num2; // May throw ArithmeticException
System.out.println("The result of division is: " + result);
} catch (ArithmeticException e) {
// Handles division by zero
System.out.println("Error: Division by zero is not allowed.");
} catch (java.util.InputMismatchException e) {
// Handles invalid input type
System.out.println("Error: Please enter valid integers.");
} finally {
// Executes no matter what
System.out.println("Execution completed.");
scanner.close();
}
}
}