An Exception is an unwanted event that occurs during program execution and disrupts the normal flow of the program.
Program:
class Demo {
public static void main(String[] args) {
int a = 10;
int b = 0;
System.out.println(a / b);
}
}
Output:
Why Exceptions Occur?
Dividing a number by zero
Accessing an invalid array index
Opening a file that does not exist
Null object access
Handling Exceptions:
class Demo {
public static void main(String[] args) {
try {
int a = 10;
int b = 0;
System.out.println(a / b);
}
catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
}
}
Output:


Top comments (0)