Assignment-5
1. What is the syntax of Exception Handling in Java? Provide an example.
**Syntax:**
try {
// Code that may cause an exception
} catch (ExceptionType e) {
// Handling the exception
} finally {
// Code that always executes
**Example:**
```java
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // Causes ArithmeticException
} catch (ArithmeticException e) {
[Link]("Exception caught: " + e);
} finally {
[Link]("Finally block executed.");
}
}
}
```
2. What is a `finally` block? Where and how is it used?
**Example:**
try {
[Link]("Inside try block");
} catch (Exception e) {
[Link]("Exception caught");
} finally {
[Link]("Finally block executed.");
}
[Link] a suitable example to demonstrate Exception Handling in Java.
public class ExceptionHandlingDemo {
public static void main(String[] args) {
try {
int[] arr = new int[5];
arr[10] = 50; // Causes ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Exception caught: " + e);
} finally {
[Link]("End of program execution.");
}
}
}
3. What is the difference between `throw` and `throws` in Java?
**Example:**
public class ThrowExample {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
} else {
[Link]("Eligible to vote");
}
}
public static void main(String[] args) {
checkAge(16); // Will throw an exception
}
}