JAVA Exception
JAVA Exception
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.
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.
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.
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:
ParseException: Indicates a problem while parsing a string into another data type, such
as parsing a date.
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
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.
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.
Keyword Description
The "try" keyword is used to specify a block where we should place an exception code.
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.
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. }
JavaExceptionExample.java
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.
1. int a=50/0;//ArithmeticException
Here's a simple Java code example where an ArithmeticException occurs:
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.
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.
1. String s=null;
2. System.out.println(s.length());//NullPointerException
Here's a Java code example where a NullPointerException occurs:
Advertisement
Inside the try block, we attempt to call the length() method on the str reference, which is
null.
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.
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
Here's a Java code example where a NumberFormatException occurs:
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.
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.
Inside the try block, we attempt to access an element at index 10, which is out of bounds
for the array numbers.
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.
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.
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.
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.
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.
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.
swer: c)
planation: Custom exceptions must inherit from the Exception class or one of its subclasses.
swer: c)
planation: The process of passing an exception from one method to its calling 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.
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:
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:
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.
Example 2
TryCatchExample2.java
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
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
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
Output:
TryCatchExample6.java
Output
Example 4
Here, we handle the exception using the parent class exception.
TryCatchExample4.java
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
TryCatchExample6.java
Output
25
Example 7
In this example, along with try block, we also enclose exception code in a catch block.
TryCatchExample7.java
Output:
Example 8
In this example, we handle the generated exception (Arithmetic Exception) with a different type
(ArrayIndexOutOfBoundsException).
TryCatchExample8.java
Output:
TryCatchExample9.java
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:
2. What happens if an exception is thrown in a try block but no matching catch block is found?
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?
Explanation: The catch block for IOException must come before the catch block
Placing the more general catch block first would make the specific 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.
MultipleCatchBlock1.java
Output:
Advertisement
Output:
MultipleCatchBlock3.java
Output:
MultipleCatchBlock4.java
Output:
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
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. ....
NestedTryBlock.java
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
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).
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 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 above code throw an unchecked exception. Similarly, we can also throw unchecked
and user defined exceptions.
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:
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:
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?
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.
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.
1.
2. public void myMethod() throws IOException, SQLException { ... }
Which of the following is true about the myMethod declaration?
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?
Answer: C