Exp 8 J
Exp 8 J
Explanation:
Exception handling is a crucial mechanism in Java that allows you to gracefully manage errors
that might occur during program execution. It prevents unexpected program termination and
enables you to provide meaningful feedback to the user.
1. try-catch block:
o The try block encloses the code that might potentially throw an exception.
o The catch block(s) handle specific exceptions thrown within the try block. You can have
multiple catch blocks to handle different exception types.
2. Nested try statements:
o You can have try blocks nested within other try blocks. This allows you to define exception
handling for different parts of your code with finer granularity.
3. throw and throws:
o The throw keyword is used to explicitly throw an exception from within a method.
o The throws keyword is used in a method declaration to indicate the types of exceptions that a
method might throw. This informs the caller that it needs to handle these exceptions
appropriately.
4. Custom exceptions:
o You can create your own exception classes by extending the built-in Exception class. This allows
you to define specialized exceptions that represent specific errors in your application domain.
Code Examples:
(i). Program using try-catch block:
Java
public class TryCatchExample {
public static void main(String[] args) {
int num1 = 10;
int num2 = 0;
try {
int result = num1 / num2; // This line might throw an ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero!");
}
System.out.println("Program continues...");
}
}
(ii). Program with nested try statements:
Java
public class NestedTryExample {
public static void main(String[] args) {
try {
int[] arr = new int[5];
arr[6] = 10; // This line might throw an ArrayIndexOutOfBoundsException
try {
int num = Integer.parseInt("hello"); // This might throw a NumberFormatException
System.out.println("Number: " + num);
} catch (NumberFormatException e) {
System.out.println("Error: Invalid number format!");
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Array index out of bounds!");
}
System.out.println("Program continues...");
}
}
(iii). Program using throw and throws:
Java
public class ThrowThrowsExample {
public static int divide(int num1, int num2) throws ArithmeticException {
if (num2 == 0) {
throw new ArithmeticException("Division by zero!"); // Explicitly throwing an exception
}
return num1 / num2;
}