Exception Handling
Exception Handling
com/java-programming
Java Exceptions
In this tutorial, we will learn about exceptions in Java. We will cover errors,
exceptions and different types of exceptions in Java.
Device failure
Code errors
Errors
Exceptions
We will learn how to handle these exceptions in the next tutorial. In this
tutorial, we will now focus on different types of exceptions in Java.
1. RuntimeException
2. IOException
An IOException is also known as a checked exception. They are checked by
the compiler at the compile-time and the programmer is prompted to handle
these exceptions.
Some of the examples of checked exceptions are:
try...catch block
finally block
throw and throws keyword
try {
// code
}
catch(Exception e) {
// code
}
Here, we have placed the code that might generate an exception inside
the try block. Every try block is followed by a catch block.
When an exception occurs, it is caught by the catch block. The catch block
cannot be used without the try block.
Example: Exception handling using try...catch
class Main {
public static void main(String[] args) {
try {
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}
Output
In the example, we are trying to divide a number by 0 . Here, this code
generates an exception.
To handle the exception, we have put the code, 5 / 0 inside the try block.
Now when an exception occurs, the rest of the code inside the try block is
skipped.
The catch block catches the exception and statements inside the catch
block is executed.
If none of the statements in the try block generates an exception,
the catch block is skipped.
try {
//code
}
catch (ExceptionType1 e1) {
// catch block
}
finally {
// finally block always executes
}
If an exception occurs, the finally block is executed after
the try...catch block. Otherwise, it is executed after the try block. For
each try block, there can be only one finally block.
class Main {
public static void main(String[] args) {
try {
// code that generates exception
int divideByZero = 5 / 0;
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
finally {
System.out.println("This is the finally block");
}
}
}
Output
In the above example, we are dividing a number by 0 inside the try block.
Here, this code generates an ArithmeticException .
The exception is caught by the catch block. And, then the finally block is
executed.
Note: It is a good practice to use the finally block. It is because it can
include important cleanup codes like,
code that might be accidentally skipped by return, continue or break
closing a file or connection
. Is the following code legal?
try {
} finally {
}
Answer: Yes, it's legal. A try statement does not have to have a catch
statement if it has a finally statement.
If the code in the try statement has multiple exit points and no associated
catch clauses,
the code in the finally statement is executed no matter how the try block is
exited.
Java provides five keywords that are used to handle the exception. The following
table describes each.
Keywor Description
d
try The "try" keyword is used to specify a block where we should place an exception code. It means
we can't use try block alone. The try block must be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block which means
we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is executed whether an
exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception
in the method. It doesn't throw an exception. It is always used with method signature.
1. int a=50/0;//ArithmeticException
1. String s=null;
2. System.out.println(s.length());//NullPointerException
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
1. int a[]=new int[5];
2. a[10]=50; //ArrayIndexOutOfBoundsException
class Main {
public static void divideByZero() {
// throw an exception
throw new ArithmeticException("Trying to divide by 0");
}
Output
import java.io.*;
class Main {
// declareing the type of exception
public static void findFile() throws IOException {
Output
Java try...catch
In this tutorial, we will learn about the try catch statement in Java with the
help of examples.
The try...catch block in Java is used to handle exceptions and prevents the
abnormal termination of the program.
Here's the syntax of a try...catch block in Java.
try{
// code
}
catch(exception) {
// code
}
The try block includes the code that might generate an exception.
The catch block includes the code that is executed when there occurs an
exception inside the try block.
Example: Java try...catch block
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}
Output
int divideByZero = 5 / 0;
Note: In Java, we can use a try block without a catch block. However, we
cannot use a catch block without a try block.
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
}
finally {
System.out.println("Finally block is always executed");
}
}
}
Output
import java.io.*;
class ListOfNumbers {
try {
System.out.println("Entering try statement");
catch (Exception e) {
System.out.println("Exception => " + e.getMessage());
}
finally {
// checking if PrintWriter has been opened
if (out != null) {
System.out.println("Closing PrintWriter");
// close PrintWriter
out.close();
}
else {
System.out.println("PrintWriter not open");
}
}
}
}
class Main {
public static void main(String[] args) {
ListOfNumbers list = new ListOfNumbers();
list.writeList();
}
}
Output
In the above example, we have created an array named list and a file
named output.txt . Here, we are trying to read data from the array and
storing to the file.
Notice the code,
Here, the size of the array is 5 and the last element of the array is at list[4] .
However, we are trying to access elements at a[5] and a[6] .
Hence, the code generates an exception that is caught by the catch block.
Since the finally block is always executed, we have included code to close
the PrintWriter inside the finally block.
It is a good practice to use finally block to include important cleanup code
like closing a file or connection.
Note: There are some cases when a finally block does not execute:
Use of System.exit() method
An exception occurs in the finally block
The death of a thread
class ListOfNumbers {
public int[] arr = new int[10];
try {
arr[10] = 11;
}
}
}
class Main {
public static void main(String[] args) {
ListOfNumbers list = new ListOfNumbers();
list.writeList();
}
}
Output
In this example, we have created an integer array named arr of size 10.
Since the array index starts from 0, the last element of the array is at arr[9] .
Notice the statement,
arr[10] = 11;
Each exception type that can be handled by the catch block is separated
using a vertical bar | .
Its syntax is:
try {
// code
} catch (ExceptionType1 | Exceptiontype2 ex) {
// catch block
}
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked
Exceptions
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and
Error are known as checked exceptions. For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions.
For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
3) Error
As you can see from the above syntax, we can use throws to declare
multiple exceptions.
import java.io.*;
class Main {
public static void findFile() throws IOException {
// code that may produce IOException
File newFile=new File("test.txt");
FileInputStream stream=new FileInputStream(newFile);
}
Output
Here's how we can throw multiple exceptions using the throws keyword.
import java.io.*;
class Main {
public static void findFile() throws NullPointerException, IOException,
InvalidClassException {
throw throwableObject;
class Main {
public static void divideByZero() {
throw new ArithmeticException("Trying to divide by 0");
}
Output
import java.io.*;
class Main {
public static void findFile() throws IOException {
throw new IOException("File not found");
}
Output
The findFile() method throws an IOException with the message we passed to
its constructor.
Note that since it is a checked exception, we must specify it in
the throws clause.
The methods that call this findFile() method need to either handle this
exception or specify it using throws keyword themselves.
We have handled this exception in the main() method. The flow of program
execution transfers from the try block to catch block when an exception is
thrown. So, the rest of the code in the try block is skipped and statements
in the catch block are executed.
1. write a java program that checks age of a person for voting. if the age is
less than 18 the program should throw an exception to prompt the user
that he/she is not eligible for voting.
public class Exception7{
void checkAge(int age){
if(age<18)
throw new ArithmeticException("Not Eligible for voting");
else
System.out.println("Eligible for voting");
}
public static void main(String args[]){
Example1 obj = new Example1();
obj.checkAge(13);
System.out.println("End Of Program");
}
}
4. Declaration throw is used within the throws is used with the method
method. signature.
1. public class TestThrow {
2. //defining a method
3. public static void checkNum(int num) {
4. if (num < 1) {
5. throw new ArithmeticException("\nNumber is negative, cannot calcula
te square");
6. }
7. else {
8. System.out.println("Square of " + num + " is " + (num*num));
9. }
10. }
11. //main method
12. public static void main(String[] args) {
13. TestThrow obj = new TestThrow();
14. obj.checkNum(-3);
15. System.out.println("Rest of the code..");
16. }
17. }
Output:
Keep Watching
1. public class TestThrows {
2. //defining a method
3. public static int divideNum(int m, int n) throws ArithmeticException {
4. int div = m / n;
5. return div;
6. }
7. //main method
8. public static void main(String[] args) {
9. TestThrows obj = new TestThrows();
10. try {
11. System.out.println(obj.divideNum(45, 0));
12. }
13. catch (ArithmeticException e){
14. System.out.println("\nNumber cannot be divided by 0");
15. }
16.
17. System.out.println("Rest of the code..");
18. }
19. }
Output:
1. public class TestThrowAndThrows
2. {
3. // defining a user-defined method
4. // which throws ArithmeticException
5. static void method() throws ArithmeticException
6. {
7. System.out.println("Inside the method()");
8. throw new ArithmeticException("throwing ArithmeticException");
9. }
10. //main method
11. public static void main(String args[])
12. {
13. try
14. {
15. method();
16. }
17. catch(ArithmeticException e)
18. {
19. System.out.println("caught in main() method");
20. }
21. }
22. }
Output:
Java catch Multiple Exceptions
In this tutorial, we will learn to handle multiple exceptions in Java with the
help of examples.
class Main {
public static void main(String[] args) {
try {
int array[] = new int[10];
array[10] = 30 / 0;
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
}
Output
/ by zero
try {
// code
} catch (ExceptionType1 | Exceptiontype2 ex) {
// catch block
}
class Main {
public static void main(String[] args) {
try {
int array[] = new int[10];
array[10] = 30 / 0;
} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
}
Output
/ by zero
class Main {
public static void main(String[] args) {
try {
int array[] = new int[10];
array[10] = 30 / 0;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Output
/ by zero
class Main {
public static void main(String[] args) {
try {
int array[] = new int[10];
array[10] = 30 / 0;
} catch (Exception | ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
}
Output
2. Applicable Final keyword is used Finally block is always finalize() method is used
to with the classes, related to the try and with the objects.
methods and variables. catch block in exception
handling.
3. Functionality (1) Once declared, final (1) finally block runs the finalize method performs
variable becomes important code even if the cleaning activities
constant and cannot be exception occurs or not. with respect to the object
modified. (2) finally block cleans up before its destruction.
(2) final method cannot all the resources used in
be overridden by sub try block
class.
(3) final class cannot be
inherited.
Along with this, there are many differences between final, finally and finalize. A list of
differences between final, finally and finalize are given below:
FinalExampleTest.java
1. public class FinalExampleTest {
2. //declaring final variable
3. final int age = 18;
4. void display() {
5.
6. // reassigning value to age variable
7. // gives compile time error
8. age = 55;
9. }
10.
11. public static void main(String[] args) {
12.
13. FinalExampleTest obj = new FinalExampleTest();
14. // gives compile time error
15. obj.display();
16. }
17. }
Output:
In the above example, we have declared a variable final. Similarly, we can declare the
methods and classes final using the final keyword.
FinallyExample.java
1. public class FinallyExample {
2. public static void main(String args[]){
3. try {
4. System.out.println("Inside try block");
5. // below code throws divide by zero exception
6. int data=25/0;
7. System.out.println(data);
8. }
9. // handles the Arithmetic Exception / Divide by zero exception
10. catch (ArithmeticException e){
11. System.out.println("Exception handled");
12. System.out.println(e);
13. }
14. // executes regardless of exception occurred or not
15. finally {
16. System.out.println("finally block is always executed");
17. }
18. System.out.println("rest of the code...");
19. }
20. }
Output:
1. public class FinalizeExample {
2. public static void main(String[] args)
3. {
4. FinalizeExample obj = new FinalizeExample();
5. // printing the hashcode
6. System.out.println("Hashcode is: " + obj.hashCode());
7. obj = null;
8. // calling the garbage collector using gc()
9. System.gc();
10. System.out.println("End of the garbage collection");
11. }
12. // defining the finalize method
13. protected void finalize()
14. {
15. System.out.println("Called the finalize() method");
16. }
17. }
Output:
https://www.javatpoint.com/difference-between-final-finally-and-finalize