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

JAVA Exception

In Java, an exception is an event that disrupts the normal flow of program execution, typically represented by an object of the java.lang.Exception class. Exception handling is a mechanism to manage runtime errors, allowing the application to maintain its flow despite exceptions. Java categorizes exceptions into checked exceptions, unchecked exceptions, and errors, each with distinct characteristics and handling requirements.

Uploaded by

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

JAVA Exception

In Java, an exception is an event that disrupts the normal flow of program execution, typically represented by an object of the java.lang.Exception class. Exception handling is a mechanism to manage runtime errors, allowing the application to maintain its flow despite exceptions. Java categorizes exceptions into checked exceptions, unchecked exceptions, and errors, each with distinct characteristics and handling requirements.

Uploaded by

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

What is Exception in Java?

In Java, an exception is an event that occurs during the execution of a program that
disrupts the normal flow of instructions. These exceptions can occur for various reasons,
such as invalid user input, file not found, or division by zero. When an exception occurs,
it is typically represented by an object of a subclass of the java.lang.Exception class.

What is Exception Handling?


Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling


The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application; that is
why we need to handle exceptions. Let's consider a scenario:

1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at
statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be
executed. However, when we perform exception handling, the rest of the statements will
be executed. That is why we use exception handling in Java.

Hierarchy of Java Exception classes


The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by
two subclasses: Exception and Error. The hierarchy of Java Exception classes is given
below:

Advantage of Exception Handling


The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application; that is
why we need to handle exceptions. Let's consider a scenario:

1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at
statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be
executed. However, when we perform exception handling, the rest of the statements will
be executed. That is why we use exception handling in Java.

Hierarchy of Java Exception classes


The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by
two subclasses: Exception and Error. The hierarchy of Java Exception classes is given
below:

Types of Java Exceptions


n Java, exceptions are categorized into two main types: checked exceptions and
unchecked exceptions. Additionally, there is a third category known as errors. Let's
delve into each of these types:
1. Checked Exception
2. Unchecked Exception
3. Error

1. Checked Exceptions
Checked exceptions are the exceptions that are checked at compile-time. This means that the
compiler verifies that the code handles these exceptions either by catching them or declaring
them in the method signature using the throws keyword. Examples of checked exceptions
include:

IOException: An exception is thrown when an input/output operation fails, such as


when reading from or writing to a file.

SQLException: It is thrown when an error occurs while accessing a database.

ParseException: Indicates a problem while parsing a string into another data type, such
as parsing a date.

ClassNotFoundException: It is thrown when an application tries to load a class through


its string name using methods like Class.forName(), but the class with the specified
name cannot be found in the classpath.

2. Unchecked Exceptions (Runtime Exceptions)


Unchecked exceptions, also known as runtime exceptions, are not checked at compile-
time. These exceptions usually occur due to programming errors, such as logic errors or
incorrect assumptions in the code. They do not need to be declared in the method
signature using the throws keyword, making it optional to handle them. Examples of
unchecked exceptions include:

NullPointerException: It is thrown when trying to access or call a method on an object


reference that is null.

ArrayIndexOutOfBoundsException: It occurs when we try to access an array element


with an invalid index.

ArithmeticException: It is thrown when an arithmetic operation fails, such as division


by zero.

IllegalArgumentException: It indicates that a method has been passed an illegal or


inappropriate argument.

3. Errors
Errors represent exceptional conditions that are not expected to be caught under normal
circumstances. They are typically caused by issues outside the control of the application,
such as system failures or resource exhaustion. Errors are not meant to be caught or
handled by application code. Examples of errors include:

OutOfMemoryError: It occurs when the Java Virtual Machine (JVM) cannot allocate
enough memory for the application.
StackOverflowError: It is thrown when the stack memory is exhausted due to
excessive recursion.

NoClassDefFoundError: It indicates that the JVM cannot find the definition of a class
that was available at compile-time.

Understanding the different types of exceptions in Java is crucial for writing robust and
reliable code. By handling exceptions appropriately, you can improve the resilience of
your applications and provide better user experiences.hierarchy of exception handling

Difference between Checked and Unchecked Exceptions


Here are the key differences between checked exceptions, unchecked exceptions
(runtime exceptions), and errors in Java:

1. Checked Exceptions:
Compile-time Check: Checked exceptions are checked at compile-time by the Java
compiler. This means that the compiler ensures that these exceptions are either caught
or declared in the method signature using the throws keyword.

Examples: Examples of checked exceptions include IOException, SQLException,


ParseException, etc.

Forced Handling: Checked exceptions enforce explicit handling, either by catching


them or declaring them to be thrown. This helps in improving code reliability and
robustness.

Recovery Possible: Checked exceptions typically represent recoverable conditions,


such as file not found or database connection failure, where the application may take
corrective action.

2. Unchecked Exceptions (Runtime Exceptions):


Not Checked at Compile-time: Unlike checked exceptions, unchecked exceptions are
not checked at compile-time. This means that the compiler does not enforce handling of
unchecked exceptions.

Examples: Examples of unchecked exceptions include NullPointerException,


ArrayIndexOutOfBoundsException, ArithmeticException, etc.

Runtime Errors: Unchecked exceptions often represent programming errors or


unexpected conditions during runtime, such as null references or array index out of
bounds.

Optional Handling: Handling of unchecked exceptions is optional. While it's good


practice to handle them for robustness, it's not mandatory.

3. Errors:
Not Meant for Handling: Errors represent exceptional conditions that are typically beyond
the control of the application and are not meant to be caught or handled by application
code.
Examples: Examples of errors include OutOfMemoryError, StackOverflowError,
NoClassDefFoundError, etc.

Critical Conditions: Errors usually indicate critical conditions, such as JVM failures or
system resource exhaustion, where the application cannot recover.

Java Exception Keywords


Java provides five keywords that are used to handle the exception. The following table
describes each.

Keyword Description

The "try" keyword is used to specify a block where we should place an exception code.

try It means we can't use try block alone.

The try block must be followed by either catch or finally.

The "catch" block is used to handle the exception.

catch It must be preceded by try block which means

we can't use catch block alone. It can be followed by finally block later.

The "finally" block is used to execute the necessary code of the program.
finally
It is executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

The "throws" keyword is used to declare exceptions.

throws It specifies that there may occur an exception in the method.

It doesn't throw an exception. It is always used with method signature.

The try-catch Block


One of the primary mechanisms for handling exceptions in Java is the try-catch block.
The try block contains the code that may throw an exception, and the catch block is
used to handle the exception if it occurs. Here's a basic example:

1. try {
2. // Code that may throw an exception
3. } catch (ExceptionType e) {
4. // Exception handling code
5. }
Handling Multiple Exceptions
You can handle multiple types of exceptions by providing multiple catch blocks, each
catching a different type of exception. This allows you to tailor your exception handling
logic based on the specific type of exception thrown. Here's an example:

1. try {
2. // Code that may throw an exception
3. } catch (IOException e) {
4. // Handle IOException
5. } catch (NumberFormatException e) {
6. // Handle NumberFormatException
7. } catch (Exception e) {
8. // Handle any other exceptions
9. }
The finally Block
In addition to try and catch, Java also provides a finally block, which allows you to
execute cleanup code, such as closing resources, regardless of whether an exception
occurs or not. The finally block is typically used to release resources that were acquired
in the try block. Here's an example:

1. try {
2. // Code that may throw an exception
3. } catch (Exception e) {
4. // Exception handling code
5. } finally {
6. // Cleanup code
7. }

Java Exception Handling Example


Let's see an example of Java Exception Handling in which we are using a try-catch
statement to handle the exception.

JavaExceptionExample.java

1. public class JavaExceptionExample{


2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
7. //rest code of the program
8. System.out.println("rest of the code...");
9. }
10. }
Test it Now

Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
In the above example, 100/0 raises an ArithmeticException which is handled by a try-
catch block.

Common Scenarios of Java Exceptions


There are given some scenarios where unchecked exceptions may occur. They are as
follows:

1) A scenario where ArithmeticException occurs


If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException
Here's a simple Java code example where an ArithmeticException occurs:

File Name: ArithmeticExceptionExample.java

1. public class ArithmeticExceptionExample {


2. public static void main(String[] args) {
3. int dividend = 10;
4. int divisor = 0;
5. try {
6. int result = dividend / divisor; // Division by zero
7. System.out.println("Result: " + result);
8. } catch (ArithmeticException e) {
9. System.out.println("Error: Division by zero is not allowed.");
10. // Additional error handling code can be added here
11. }
12. }
13. }
Output:

Error: Division by zero is not allowed.


Explanation

We have a main() method where we attempt to perform division by zero that is not
allowed in arithmetic.

Inside the try block, we perform the division operation dividend / divisor, where divisor is
assigned the value of 0.

When the division by zero occurs, an ArithmeticException is thrown. We catch this


exception using a catch block specifically for ArithmeticException.

In the catch block, we handle the exception by printing an error message, indicating that
division by zero is not allowed. Additional error handling logic can be added here if
needed.

2) A scenario where NullPointerException occurs


If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.

1. String s=null;
2. System.out.println(s.length());//NullPointerException
Here's a Java code example where a NullPointerException occurs:

Advertisement

File Name: NullPointerExceptionExample.java

1. public class NullPointerExceptionExample {


2. public static void main(String[] args) {
3. String str = null; // Initializing a String variable to null
4. try {
5. int length = str.length(); // Attempting to call a method on a null reference
6. System.out.println("Length of the string: " + length);
7. } catch (NullPointerException e) {
8. System.out.println("Error: Null reference encountered.");
9. // Additional error handling code can be added here
10. }
11. }
12. }
Output:

Error: Null reference encountered.


Explanation

We have a main() method where we initialize a String variable str to null.

Inside the try block, we attempt to call the length() method on the str reference, which is
null.

When attempting to call a method on a null reference, a NullPointerException is thrown.

We catch this exception using a catch block specifically for NullPointerException.

In the catch block, we handle the exception by printing an error message indicating that
a null reference was encountered. Additional error handling logic can be added here if
needed.

3) A scenario where NumberFormatException occurs


If the formatting of any variable or number is mismatched, it may result into
NumberFormatException. Suppose we have a string variable that has characters;
converting this variable into digit will cause NumberFormatException.

1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
Here's a Java code example where a NumberFormatException occurs:

File Name: NumberFormatExceptionExample.java


1. public class NumberFormatExceptionExample {
2. public static void main(String[] args) {
3. String str = "abc"; // Initializing a String with non-numeric characters
4. try {
5. int num = Integer.parseInt(str); // Attempting to parse a non-
numeric string to an integer
6. System.out.println("Parsed number: " + num);
7. } catch (NumberFormatException e) {
8. System.out.println("Error: Unable to parse the string as an integer.");
9. // Additional error handling code can be added here
10. }
11. }
12. }
Output:

Error: Unable to parse the string as an integer.


Explanation:

We have a main() method where we initialize a String variable str with non-numeric
characters.

Inside the try block, we attempt to parse the string str to an integer using the
Integer.parseInt() method.

Since the string contains non-numeric characters, the parsing operation throws a
NumberFormatException.

We catch this exception using a catch block specifically for NumberFormatException.

In the catch block, we handle the exception by printing an error message indicating that
the string could not be parsed as an integer. Additional error handling logic can be
added here if needed.

4) A scenario where ArrayIndexOutOfBoundsException occurs


When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there
may be other reasons to occur ArrayIndexOutOfBoundsException. Consider the
following statements.

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException
Here's a Java code example where an ArrayIndexOutOfBoundsException occurs:

File Name: ArrayIndexOutOfBoundsExceptionExample.java

1. public class ArrayIndexOutOfBoundsExceptionExample {


2. public static void main(String[] args) {
3. int[] numbers = {1, 2, 3, 4, 5}; // Initializing an array with 5 elements
4. try {
5. int index = 10; // Accessing an index that is out of bounds
6. int value = numbers[index]; // Attempting to access an element at an invalid index
7. System.out.println("Value at index " + index + ": " + value);
8. } catch (ArrayIndexOutOfBoundsException e) {
9. System.out.println("Error: Index is out of bounds.");
10. // Additional error handling code can be added here
11. }
12. }
13. }
Output:

Error: Index is out of bounds.


Explanation

We have a main() method where we initialize an array numbers with 5 elements.

Inside the try block, we attempt to access an element at index 10, which is out of bounds
for the array numbers.

Since the index is out of bounds, an ArrayIndexOutOfBoundsException is thrown.

We catch this exception using a catch block specifically for


ArrayIndexOutOfBoundsException.

In the catch block, we handle the exception by printing an error message indicating that
the index is out of bounds. Additional error handling logic can be added here if needed.

Best Practices for Exception Handling


Catch Specific Exceptions: Catch specific exceptions whenever possible rather than
catching general Exception objects. It helps in providing more precise error handling and
makes your code easier to understand and maintain.

Keep Exception Handling Simple: Avoid overly complex exception handling logic.
Keep your catch blocks concise and focused on handling the specific exception they are
designed for. Complex exception handling logic can make your code difficult to debug
and maintain.

Log Exceptions: Always log exceptions or error messages when handling them. This
helps in troubleshooting issues and diagnosing problems in production environments.

Throw Exceptions Appropriately: Throw exceptions when necessary, but avoid


excessive use of checked exceptions. Checked exceptions should be used for
exceptional conditions that the caller can reasonably be expected to handle.

Use Custom Exceptions: Create custom exception classes for specific error conditions
in your application. This helps in providing meaningful error messages and makes your
code more self-documenting.

Conclusion
Exception handling is an essential aspect of Java programming. By following best
practices and adopting effective exception handling strategies, you can write more
robust and maintainable Java applications. Remember to catch specific exceptions,
keep exception handling simple, log exceptions for debugging purposes, throw
exceptions appropriately, and use custom exceptions when needed. Mastering
exception handling will help you build more reliable software that gracefully handles
errors and exceptions.

Java Exception Handling MCQ


What happens if a method throws a checked exception that it does not declare?

1. Compilation error
2. Runtime error
3. The program terminates without any error
4. The method catches the exception automatically

swer: a)

planation: If a method throws a checked exception that it does not declare, it causes a compilation error.

Which of the following is true about the finally block?

1. It is always executed after the try block, regardless of whether an exception was thrown.
2. It is executed only if an exception occurs.
3. It must follow a catch block.
4. It is executed only if no exception occurs.

swer: a)

planation: The finally block is always executed after the try block, regardless of whether an exception was thrown.

What type of exception is NullPointerException?

1. Checked exception
2. Unchecked exception
3. Error
4. None of the above

swer: b)

planation: NullPointerException is an unchecked exception, meaning it does not need to be declared or caught.

Which of the following statements about custom exceptions is true?

1. Custom exceptions cannot inherit from other exceptions.


2. Custom exceptions must inherit from the Throwable class.
3. Custom exceptions must inherit from Exception or its subclasses.
4. Custom exceptions can only be unchecked exceptions.

swer: c)

planation: Custom exceptions must inherit from the Exception class or one of its subclasses.

What is exception propagation in Java?

1. The process of creating and throwing custom exceptions


2. The process of handling multiple exceptions in a single try-catch block
3. The process of passing an exception from one method to its calling method
4. The process of catching and handling exceptions in nested try-catch blocks

swer: c)

planation: The process of passing an exception from one method to its calling method

Java try-catch block


Java try block
Java try block is used to enclose the code that might throw an exception. It must be
used within the method.

If an exception occurs at the particular statement in the try block, the rest of the block
code will not execute. So, it is recommended not to keep the code in try block that will
not throw an exception.

Java try block must be followed by either catch or finally block.

Syntax of Java try-catch


1. try{
2. //code that may throw an exception
3. }catch(Exception_class_Name ref){}
Syntax of try-finally block
1. try{
2. //code that may throw an exception
3. }finally{}
Java catch block
Java catch block is used to handle the Exception by declaring the type of exception
within the parameter. The declared exception must be the parent class exception ( i.e.,
Exception) or the generated exception type. However, the good approach is to declare
the generated type of exception.

can use multiple catch block with a single try block.

Internal Working of Java try-catch block

The JVM firstly checks whether the exception is handled or not. If exception is not
handled, JVM provides a default exception handler that performs the following tasks:

o Prints out exception description.


o Prints the stack trace (Hierarchy of methods where the exception occurred).
o Causes the program to terminate.
But if the application programmer handles the exception, the normal flow of the
application is maintained, i.e., rest of the code is executed.

Problem without exception handling


Let's try to understand the problem if we don't use a try-catch block.

Example 1
TryCatchExample1.java
1. public class TryCatchExample1 {
2.
3. public static void main(String[] args) {
4.
5. int data=50/0; //may throw exception
6.
7. System.out.println("rest of the code");
8.
9. }
10.
11. }
Test it Now

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero


As displayed in the above example, the rest of the code is not executed (in such case,
the rest of the code statement is not printed).

There might be 100 lines of code after the exception. If the exception is not handled, all
the code below the exception won't be executed.

Solution by exception handling


Let's see the solution of the above problem by a java try-catch block.

Example 2
TryCatchExample2.java

1. public class TryCatchExample2 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. //handling the exception
9. catch(ArithmeticException e)
10. {
11. System.out.println(e);
12. }
13. System.out.println("rest of the code");
14. }
15.
16. }
Test it Now

Output:

java.lang.ArithmeticException: / by zero
rest of the code
As displayed in the above example, the rest of the code is executed, i.e., the rest of
the code statement is printed.
Example 3
In this example, we also kept the code in a try block that will not throw an exception.

TryCatchExample3.java

1. public class TryCatchExample3 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. // if exception occurs, the remaining statement will not exceute
8. System.out.println("rest of the code");
9. }
10. // handling the exception
11. catch(ArithmeticException e)
12. {
13. System.out.println(e);
14. }
15.
16. }
17.
18. }
Test it Now

Output:

java.lang.ArithmeticException: / by zero
Here, we can see that if an exception occurs in the try block, the rest of the block code
will not execute.

Example 4
Here, we handle the exception using the parent class exception.

TryCatchExample4.java

1. public class TryCatchExample4 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. // handling the exception by using Exception class
9. catch(Exception e)
10. {
11. System.out.println(e);
12. }
13. System.out.println("rest of the code");
14. }
15.
16. }
Test it Now
Output:

java.lang.ArithmeticException: / by zero
rest of the code
Example 5
Let's see an example to print a custom message on exception.

TryCatchExample5.java

1. public class TryCatchExample5 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. // handling the exception
9. catch(Exception e)
10. {
11. // displaying the custom message
12. System.out.println("Can't divided by zero");
13. }
14. }
15.
16. }
Test it Now

Output:

Can't divided by zero


Example 6
Let's see an example to resolve the exception in a catch block.

TryCatchExample6.java

1. public class TryCatchExample6 {


2.
3. public static void main(String[] args) {
4. int i=50;
5. int j=0;
6. int data;
7. try
8. {
9. data=i/j; //may throw exception
10. }
11. // handling the exception
12. catch(Exception e)
13. {
14. // resolving the exception in catch block
15. System.out.println(i/(j+2));
16. }
17. }
18. }
Test it Now

Output

Example 4
Here, we handle the exception using the parent class exception.

TryCatchExample4.java

1. public class TryCatchExample4 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. // handling the exception by using Exception class
9. catch(Exception e)
10. {
11. System.out.println(e);
12. }
13. System.out.println("rest of the code");
14. }
15.
16. }
Test it Now

Output:

java.lang.ArithmeticException: / by zero
rest of the code
Example 5
Let's see an example to print a custom message on exception.

TryCatchExample5.java

1. public class TryCatchExample5 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. // handling the exception
9. catch(Exception e)
10. {
11. // displaying the custom message
12. System.out.println("Can't divided by zero");
13. }
14. }
15.
16. }
Test it Now
Output:

Can't divided by zero


Example 6
Let's see an example to resolve the exception in a catch block.

TryCatchExample6.java

1. public class TryCatchExample6 {


2.
3. public static void main(String[] args) {
4. int i=50;
5. int j=0;
6. int data;
7. try
8. {
9. data=i/j; //may throw exception
10. }
11. // handling the exception
12. catch(Exception e)
13. {
14. // resolving the exception in catch block
15. System.out.println(i/(j+2));
16. }
17. }
18. }
Test it Now

Output

25

Example 7
In this example, along with try block, we also enclose exception code in a catch block.

TryCatchExample7.java

1. public class TryCatchExample7 {


2.
3. public static void main(String[] args) {
4.
5. try
6. {
7. int data1=50/0; //may throw exception
8.
9. }
10. // handling the exception
11. catch(Exception e)
12. {
13. // generating the exception in catch block
14. int data2=50/0; //may throw exception
15.
16. }
17. System.out.println("rest of the code");
18. }
19. }
Test it Now

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero


Here, we can see that the catch block didn't contain the exception code. So, enclose exception code within a try
block only to handle the exceptions.

Example 8
In this example, we handle the generated exception (Arithmetic Exception) with a different type
(ArrayIndexOutOfBoundsException).

TryCatchExample8.java

1. public class TryCatchExample8 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7.
8. }
9. // try to handle the ArithmeticException using ArrayIndexOutOfBoundsException
10. catch(ArrayIndexOutOfBoundsException e)
11. {
12. System.out.println(e);
13. }
14. System.out.println("rest of the code");
15. }
16.
17. }
Test it Now

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero


Example 9
Let's see an example to handle another unchecked exception.

TryCatchExample9.java

1. public class TryCatchExample9 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int arr[]= {1,3,5,7};
7. System.out.println(arr[10]); //may throw exception
8. }
9. // handling the array exception
10. catch(ArrayIndexOutOfBoundsException e)
11. {
12. System.out.println(e);
13. }
14. System.out.println("rest of the code");
15. }
16.
17. }
Test it Now

Output:

java.lang.ArrayIndexOutOfBoundsException: 10
rest of the code
Example 10
Let's see an example to handle checked exception.

TryCatchExample10.java

1. import java.io.FileNotFoundException;
2. import java.io.PrintWriter;
3.
4. public class TryCatchExample10 {
5.
6. public static void main(String[] args) {
7.
8.
9. PrintWriter pw;
10. try {
11. pw = new PrintWriter("jtp.txt"); //may throw exception
12. pw.println("saved");
13. }
14. // providing the checked exception handler
15. catch (FileNotFoundException e) {
16.
17. System.out.println(e);
18. }
19. System.out.println("File saved successfully");
20. }
21. }
Test it Now

Output:

File saved successfully


Java try catch block MCQ
1. Which of the following is true about the catch block in Java?

1. It must be followed by a finally block.


2. It can catch multiple types of exceptions in a single block.
3. It must specify the type of exception it can handle.
4. It can only catch unchecked exceptions.

Show Answer Workspace

2. What happens if an exception is thrown in a try block but no matching catch block is found?

1. The program terminates immediately.


2. The exception is caught by the default handler.
3. The exception is propagated up the call stack.
4. The finally block is skipped.

Show Answer Workspace

3. In which scenario would a finally block not execute?

1. When an exception is thrown and not caught.


2. When a System.exit() call is made in the try block.
3. When an exception is caught by a catch block.
4. When the try block completes normally.

Show Answer Workspace

4. Which statement about nested try-catch blocks is correct?

1. Only the innermost catch block can handle exceptions.


2. Exceptions can be caught by any matching catch block at any level.
3. Nested try-catch blocks are not allowed in Java.
4. A try block cannot be nested inside another try block.

Show Answer Workspace

5. Consider the following code:

1.
2. try {
3. // Code that might throw exceptions
4. } catch (IOException e) {
5. // Handle IOException
6. } catch (Exception e) {
7. // Handle all other exceptions
8. }
Which statement is true regarding the order of catch blocks?

1. The catch blocks can be in any order.


2. The catch block for Exception should come before IOException.
3. The catch block for IOException should come before Exception.
4. The catch blocks must be followed by a finally block.

Next Topic Answer: C

Explanation: The catch block for IOException must come before the catch block

for Exception because IOException is a subclass of Exception.

Placing the more general catch block first would make the specific catch block

unreachable and cause a compilation error.

Java Catch Multiple Exceptions


Java Multi-catch block
A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.

Points to remember
o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.

Flowchart of Multi-catch Block


Example 1
Let's see a simple example of java multi-catch block.

MultipleCatchBlock1.java

1. public class MultipleCatchBlock1 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7. a[5]=30/0;
8. }
9. catch(ArithmeticException e)
10. {
11. System.out.println("Arithmetic Exception occurs");
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. System.out.println("ArrayIndexOutOfBounds Exception occurs");
16. }
17. catch(Exception e)
18. {
19. System.out.println("Parent Exception occurs");
20. }
21. System.out.println("rest of the code");
22. }
23. }
Test it Now

Output:

Advertisement

Arithmetic Exception occurs


rest of the code
Example 2
MultipleCatchBlock2.java

1. public class MultipleCatchBlock2 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7.
8. System.out.println(a[10]);
9. }
10. catch(ArithmeticException e)
11. {
12. System.out.println("Arithmetic Exception occurs");
13. }
14. catch(ArrayIndexOutOfBoundsException e)
15. {
16. System.out.println("ArrayIndexOutOfBounds Exception occurs");
17. }
18. catch(Exception e)
19. {
20. System.out.println("Parent Exception occurs");
21. }
22. System.out.println("rest of the code");
23. }
24. }
Test it Now

Output:

ArrayIndexOutOfBounds Exception occurs


rest of the code
In this example, try block contains two exceptions. But at a time only one exception occurs and
its corresponding catch block is executed.

MultipleCatchBlock3.java

1. public class MultipleCatchBlock3 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7. a[5]=30/0;
8. System.out.println(a[10]);
9. }
10. catch(ArithmeticException e)
11. {
12. System.out.println("Arithmetic Exception occurs");
13. }
14. catch(ArrayIndexOutOfBoundsException e)
15. {
16. System.out.println("ArrayIndexOutOfBounds Exception occurs");
17. }
18. catch(Exception e)
19. {
20. System.out.println("Parent Exception occurs");
21. }
22. System.out.println("rest of the code");
23. }
24. }
Test it Now

Output:

Arithmetic Exception occurs


rest of the code
Example 4
In this example, we generate NullPointerException, but didn't provide the corresponding
exception type. In such case, the catch block containing the parent exception class Exception will
invoked.

MultipleCatchBlock4.java

1. public class MultipleCatchBlock4 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. String s=null;
7. System.out.println(s.length());
8. }
9. catch(ArithmeticException e)
10. {
11. System.out.println("Arithmetic Exception occurs");
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. System.out.println("ArrayIndexOutOfBounds Exception occurs");
16. }
17. catch(Exception e)
18. {
19. System.out.println("Parent Exception occurs");
20. }
21. System.out.println("rest of the code");
22. }
23. }
Test it Now

Output:

Parent Exception occurs


rest of the code
Example 5
Let's see an example, to handle the exception without maintaining the order of exceptions (i.e.
from most specific to most general).

MultipleCatchBlock5.java

1. class MultipleCatchBlock5{
2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(Exception e){System.out.println("common task completed");}
8. catch(ArithmeticException e){System.out.println("task1 is completed");}
9. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
10. System.out.println("rest of the code...");
11. }
12. }
Test it Now

Output:

Compile-time error

Next T

Java Nested try block


In Java, using a try block inside another try block is permitted. It is called as nested try
block. Every statement that we enter a statement in try block, context of that exception is
pushed onto the stack.

For example, the inner try block can be used to


handle ArrayIndexOutOfBoundsException while the outer try block can handle
the ArithemeticException (division by zero).

Why use nested try block


Sometimes a situation may arise where a part of a block may cause one error and the
entire block itself may cause another error. In such cases, exception handlers have to be
nested.

Syntax:
1. ....
2. //main try block
3. try
4. {
5. statement 1;
6. statement 2;
7. //try catch block within another try block
8. try
9. {
10. statement 3;
11. statement 4;
12. //try catch block within nested try block
13. try
14. {
15. statement 5;
16. statement 6;
17. }
18. catch(Exception e2)
19. {
20. //exception message
21. }
22.
23. }
24. catch(Exception e1)
25. {
26. //exception message
27. }
28. }
29. //catch block of parent (outer) try block
30. catch(Exception e3)
31. {
32. //exception message
33. }
34. ....

Java Nested try Example


Example 1
Let's see an example where we place a try block within another try block for two different
exceptions.

NestedTryBlock.java

1. public class NestedTryBlock{


2. public static void main(String args[]){
3. //outer try block
4. try{
5. //inner try block 1
6. try{
7. System.out.println("going to divide by 0");
8. int b =39/0;
9. }
10. //catch block of inner try block 1
11. catch(ArithmeticException e)
12. {
13. System.out.println(e);
14. }
15.
16.
17. //inner try block 2
18. try{
19. int a[]=new int[5];
20.
21. //assigning the value out of array bounds
22. a[5]=4;
23. }
24.
25. //catch block of inner try block 2
26. catch(ArrayIndexOutOfBoundsException e)
27. {
28. System.out.println(e);
29. }
30.
31.
32. System.out.println("other statement");
33. }
34. //catch block of outer try block
35. catch(Exception e)
36. {
37. System.out.println("handled the exception (outer catch)");
38. }
39.
40. System.out.println("normal flow..");
41. }
42. }
Output:

When any try block does not have a catch block for a particular exception, then the
catch block of the outer (parent) try block are checked for that exception, and if it
matches, the catch block of outer try block is executed.
If none of the catch block specified in the code is unable to handle the exception, then
the Java runtime system will handle the exception. Then it displays the system
generated message for that exception.

Example 2
Let's consider the following example. Here the try block within nested try block (inner try
block 2) do not handle the exception. The control is then transferred to its parent try
block (inner try block 1). If it does not handle the exception, then the control is
transferred to the main try block (outer try block) where the appropriate catch block
handles the exception. It is termed as nesting.

NestedTryBlock.java

1. public class NestedTryBlock2 {


2.
3. public static void main(String args[])
4. {
5. // outer (main) try block
6. try {
7.
8. //inner try block 1
9. try {
10.
11. // inner try block 2
12. try {
13. int arr[] = { 1, 2, 3, 4 };
14.
15. //printing the array element out of its bounds
16. System.out.println(arr[10]);
17. }
18.
19. // to handles ArithmeticException
20. catch (ArithmeticException e) {
21. System.out.println("Arithmetic exception");
22. System.out.println(" inner try block 2");
23. }
24. }
25.
26. // to handle ArithmeticException
27. catch (ArithmeticException e) {
28. System.out.println("Arithmetic exception");
29. System.out.println("inner try block 1");
30. }
31. }
32.
33. // to handle ArrayIndexOutOfBoundsException
34. catch (ArrayIndexOutOfBoundsException e4) {
35. System.out.print(e4);
36. System.out.println(" outer (main) try block");
37. }
38. catch (Exception e5) {
39. System.out.print("Exception");
40. System.out.println(" handled in main try-block");
41. }
42. }
43. }
Output:

Rule: For each try block there can be zero or more catch blocks, but only
one finally block.
Note: The finally block will not be executed if the program exits (either
by calling System.exit() or by causing a fatal error that causes the
process to abort).

Java throw Exception


In Java, exceptions allows us to write good quality codes where the errors are checked
at the compile time instead of runtime and we can create custom exceptions making the
code recovery and debugging easier.

Java throw keyword


The Java throw keyword is used to throw an exception explicitly.

We specify the exception object which is to be thrown. The Exception has some
message with it that provides the error description. These exceptions may be related to
user inputs, server, etc.

We can throw either checked or unchecked exceptions in Java by throw keyword. It is


mainly used to throw a custom exception. We will discuss custom exceptions later in this
section.

We can also define our own set of conditions and throw an exception explicitly using
throw keyword. For example, we can throw ArithmeticException if we divide a number by
another number. Here, we just need to set the condition and throw exception using
throw keyword.

The syntax of the Java throw keyword is given below.

throw Instance i.e.,

1. throw new exception_class("error message");


Let's see the example of throw IOException.
1. throw new IOException("sorry device error");
Where the Instance must be of type Throwable or subclass of Throwable. For example,
Exception is the sub class of Throwable and the user-defined exceptions usually extend
the Exception class.

Java throw keyword Example


Example 1: Throwing Unchecked Exception
In this example, we have created a method named validate() that accepts an integer as
a parameter. If the age is less than 18, we are throwing the ArithmeticException
otherwise print a message welcome to vote.

File Name: TestThrow1.java

1. public class TestThrow1 {


2. //function to check if person is eligible to vote or not
3. public static void validate(int age) {
4. if(age<18) {
5. //throw Arithmetic exception if not eligible to vote
6. throw new ArithmeticException("Person is not eligible to vote");
7. }
8. else {
9. System.out.println("Person is eligible to vote!!");
10. }
11. }
12. //main method
13. public static void main(String args[]){
14. //calling the function
15. validate(13);
16. System.out.println("rest of the code...");
17. }
18. }
Output:

The above code throw an unchecked exception. Similarly, we can also throw unchecked
and user defined exceptions.

Note: If we throw an unchecked exception from a method, it is not


required to handle the exception or declare it in throws clause. However,
for checked exceptions, handling or declaration in the throws clause is
mandatory."
If we throw a checked exception using throw keyword, it is must to handle the exception
using catch block or the method must declare it using throws declaration.

Example 2: Throwing Checked Exception


Note: Every subclass of Error and RuntimeException is an unchecked
exception in Java. A checked exception is everything else under the
Throwable class.
File Name: TestThrow2.java

1. import java.io.*;
2.
3. public class TestThrow2 {
4.
5. //function to check if person is eligible to vote or not
6. public static void method() throws FileNotFoundException {
7.
8. FileReader file = new FileReader("C:\\Users\\Anurati\\Desktop\\abc.txt");
9. BufferedReader fileInput = new BufferedReader(file);
10.
11.
12. throw new FileNotFoundException();
13.
14. }
15. //main method
16. public static void main(String args[]){
17. try
18. {
19. method();
20. }
21. catch (FileNotFoundException e)
22. {
23. e.printStackTrace();
24. }
25. System.out.println("rest of the code...");
26. }
27. }
Output:

Example 3: Throwing User-defined Exception


exception is everything else under the Throwable class.

TestThrow3.java
1. // class represents user-defined exception
2. class UserDefinedException extends Exception
3. {
4. public UserDefinedException(String str)
5. {
6. // Calling constructor of parent Exception
7. super(str);
8. }
9. }
10. // Class that uses above MyException
11. public class TestThrow3
12. {
13. public static void main(String args[])
14. {
15. try
16. {
17. // throw an object of user defined exception
18. throw new UserDefinedException("This is user-defined exception");
19. }
20. catch (UserDefinedException ude)
21. {
22. System.out.println("Caught the exception");
23. // Print the message from MyException object
24. System.out.println(ude.getMessage());
25. }
26. }
27. }

Output:

Java throw keyword MCQ


1. Which of the following is true about the throw keyword in Java?

1. It is used to declare an exception.


2. It is used to handle an exception.
3. It is used to explicitly throw an exception.
4. It is used to define a custom exception.

Answer: C
Explanation: The throw keyword in Java is used to explicitly throw an exception, either
a checked or unchecked exception, from any part of the code. It is different from
exception handling, which is done using try, catch, and finally.

2. When a method throws a checked exception, what must the method declare?

1. It must declare the exception using the throws keyword.


2. It must catch the exception within the method.
3. It must use a try block within the method.
4. It must ignore the exception.

Answer: A

Explanation: When a method throws a checked exception, it must declare that it throws
the exception using the throws keyword in its method signature. It informs callers of the
method that they must handle or further declare the exception.

3. Which of the following statements is false regarding custom exceptions in


Java?

1. Custom exceptions must extend the Exception class.


2. Custom exceptions can extend the RuntimeException class.
3. Custom exceptions cannot have constructors.
4. Custom exceptions can include additional methods and fields.

Answer: C

Explanation: This statement is false because custom exceptions can and often do have
constructors. These constructors can be used to provide custom error messages or
other details when the exception is thrown.

4. Consider the following method signature:

1.
2. public void myMethod() throws IOException, SQLException { ... }
Which of the following is true about the myMethod declaration?

1. myMethod() must handle both IOException and SQLException within the


method.
2. myMethod() must not throw any exceptions.
3. myMethod() declares that it may throw IOException and SQLException, and
these must be handled by its caller.
4. myMethod() can only throw IOException and not SQLException.

Answer: C
Explanation: The method myMethod() declares that it may throw IOException and
SQLException. Any caller of myMethod() must handle these exceptions using a try-catch
block or declare them in its own throws clause.

5. Which of the following correctly describes the behavior of the finally block
when an exception is thrown?

1. The finally block is executed only if no exception is thrown.


2. The finally block is executed only if an exception is thrown.
3. The finally block is executed regardless of whether an exception is thrown.
4. The finally block is executed only for unchecked exceptions.

Answer: C

Explanation: The finally block is always executed, regardless of whether an exception is


thrown or not. It is typically used for resource cleanup, such as closing files or releasing
network resources, ensuring that these actions occur under all circumstances.

You might also like