0% found this document useful (0 votes)
2 views

Assignment5

The document explains the syntax of Exception Handling in Java, including the use of try, catch, and finally blocks with examples. It also describes the purpose of the finally block and demonstrates exception handling through a specific example. Additionally, it clarifies the difference between 'throw' and 'throws' in Java with an example of throwing an exception based on age eligibility.

Uploaded by

nikku
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Assignment5

The document explains the syntax of Exception Handling in Java, including the use of try, catch, and finally blocks with examples. It also describes the purpose of the finally block and demonstrates exception handling through a specific example. Additionally, it clarifies the difference between 'throw' and 'throws' in Java with an example of throwing an exception based on age eligibility.

Uploaded by

nikku
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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) {
System.out.println("Exception caught: " + e);
} finally {
System.out.println("Finally block executed.");
}
}
}
```

2. What is a `finally` block? Where and how is it used?

**Example:**
try {
System.out.println("Inside try block");
} catch (Exception e) {
System.out.println("Exception caught");
} finally {
System.out.println("Finally block executed.");
}
3.Provide 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) {
System.out.println("Exception caught: " + e);
} finally {
System.out.println("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 {
System.out.println("Eligible to vote");
}
}

public static void main(String[] args) {


checkAge(16); // Will throw an exception
}
}

You might also like