https://www.programiz.
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.
An exception is an unexpected event that occurs during program execution.
It affects the flow of the program instructions which can cause the program
to terminate abnormally.
An exception can occur for many reasons. Some of them are:
Invalid user input
Device failure
Loss of network connection
Physical limitations (out of disk memory)
Code errors
Opening an unavailable file
Java Exception hierarchy
Here is a simplified diagram of the exception hierarchy in Java.
As you can see from the image above, the Throwable class is the root class
in the hierarchy.
Note that the hierarchy splits into two branches: Error and Exception.
Errors
Errors represent irrecoverable conditions such as Java virtual machine
(JVM) running out of memory, memory leaks, stack overflow errors, library
incompatibility, infinite recursion, etc.
Errors are usually beyond the control of the programmer and we should not
try to handle errors.
Exceptions
Exceptions can be caught and handled by the program.
When an exception occurs within a method, it creates an object. This object
is called the exception object.
It contains information about the exception such as the name and
description of the exception and state of the program when the exception
occurred.
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.
Java Exception Types
The exception hierarchy also has two
branches: RuntimeException and IOException .
1. RuntimeException
A runtime exception happens due to a programming error. They are also
known as unchecked exceptions.
These exceptions are not checked at compile-time but run-time. Some of
the common runtime exceptions are:
Improper use of an API - IllegalArgumentException
Null pointer access (missing the initialization of a variable)
- NullPointerException
Out-of-bounds array access - ArrayIndexOutOfBoundsException
Dividing a number by 0 - ArithmeticException
You can think about it in this way. “If it is a runtime exception, it is your
fault”.
The NullPointerException would not have occurred if you had checked
whether the variable was initialized or not before using it.
An ArrayIndexOutOfBoundsException would not have occurred if you tested the
array index against the array bounds.
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:
Trying to open a file that doesn’t exist results in FileNotFoundException
Trying to read past the end of a file
Java Exception Handling
In the tutorial, we will learn about different approaches of exception
handling in Java with the help of examples.
We know that exceptions abnormally terminate the execution of a program.
This is why it is important to handle exceptions. Here's a list of different
approaches to handle exceptions in Java.
try...catch block
finally block
throw and throws keyword
1. Java try...catch block
The try-catch block is used to handle exceptions in Java. Here's the syntax
of try...catch block:
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 {
// code that generate exception
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}
Output
ArithmeticException => / by zero
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.
2. Java finally block
In Java, the finally block is always executed no matter whether there is an
exception or not.
The finally block is optional. And, for each try block, there can be only
one finally block.
The basic syntax of finally block is:
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.
Example: Java Exception Handling using 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
ArithmeticException => / by zero
This is the finally block
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 Exception Keywords
https://www.javatpoint.com/exception-handling-in-java
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.
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
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
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
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
3. Java throw and throws keyword
The Java throw keyword is used to explicitly throw a single exception.
When we throw an exception, the flow of the program moves from
the try block to the catch block.
Example: Exception handling using Java throw
class Main {
public static void divideByZero() {
// throw an exception
throw new ArithmeticException("Trying to divide by 0");
}
public static void main(String[] args) {
divideByZero();
}
}
Output
Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0
at Main.divideByZero(Main.java:5)
at Main.main(Main.java:9)
In the above example, we are explicitly throwing the ArithmeticException using
the throw keyword.
Similarly, the throws keyword is used to declare the type of exceptions that
might occur within the method. It is used in the method declaration.
Example: Java throws keyword
import java.io.*;
class Main {
// declareing the type of exception
public static void findFile() throws IOException {
// code that may generate IOException
File newFile = new File("test.txt");
FileInputStream stream = new FileInputStream(newFile);
}
public static void main(String[] args) {
try {
findFile();
}
catch (IOException e) {
System.out.println(e);
}
}
}
Output
java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
When we run this program, if the file test.txt does not
exist, FileInputStream throws a FileNotFoundException which extends
the IOException class.
The findFile() method specifies that an IOException can be thrown.
The main() method calls this method and handles the exception if it is
thrown.
If a method does not handle exceptions, the type of exceptions that may
occur within it must be specified in the throws clause.
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
ArithmeticException => / by zero
In the above example, notice the line,
int divideByZero = 5 / 0;
Here, we are trying to divide a number by zero. In this case, an exception
occurs. Hence, we have enclosed this code inside the try block.
When the program encounters this code, ArithmeticException occurs. And, the
exception is caught by the catch block and executes the code inside
the catch block.
The catch block is only executed if there exists an exception inside
the try block.
Note: In Java, we can use a try block without a catch block. However, we
cannot use a catch block without a try block.
Java try...finally block
We can also use the try block along with a finally block.
In this case, the finally block is always executed whether there is an
exception inside the try block or not.
Example: Java try...finally block
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
}
finally {
System.out.println("Finally block is always executed");
}
}
}
Output
Finally block is always executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:4)
In the above example, we have used the try block along with
the finally block. We can see that the code inside the try block is causing
an exception.
However, the code inside the finally block is executed irrespective of the
exception.
Java try...catch...finally block
In Java, we can also use the finally block after the try...catch block. For
example,
import java.io.*;
class ListOfNumbers {
// create an integer array
private int[] list = {5, 6, 8, 9, 2};
// method to write data from array to a fila
public void writeList() {
PrintWriter out = null;
try {
System.out.println("Entering try statement");
// creating a new file OutputFile.txt
out = new PrintWriter(new FileWriter("OutputFile.txt"));
// writing values from list array to Output.txt
for (int i = 0; i < 7; i++) {
out.println("Value at: " + i + " = " + list[i]);
}
}
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
Entering try statement
Exception => Index 5 out of bounds for length 5
Closing PrintWriter
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,
for (int i = 0; i < 7; i++) {
out.println("Value at: " + i + " = " + list[i]);
}
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
Multiple Catch blocks
For each try block, there can be zero or more catch blocks.
Multiple catch blocks allow us to handle each exception differently.
The argument type of each catch block indicates the type of exception that
can be handled by it. For example,
class ListOfNumbers {
public int[] arr = new int[10];
public void writeList() {
try {
arr[10] = 11;
}
catch (NumberFormatException e1) {
System.out.println("NumberFormatException => " + e1.getMessage());
}
catch (IndexOutOfBoundsException e2) {
System.out.println("IndexOutOfBoundsException => " + e2.getMessage());
}
}
}
class Main {
public static void main(String[] args) {
ListOfNumbers list = new ListOfNumbers();
list.writeList();
}
}
Output
IndexOutOfBoundsException => Index 10 out of bounds for length 10
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;
Here, we are trying to assign a value to the index 10.
Hence, IndexOutOfBoundException occurs.
When an exception occurs in the try block,
The exception is thrown to the first catch block. The first catch block
does not handle an IndexOutOfBoundsException , so it is passed to the
next catch block.
The second catch block in the above example is the appropriate
exception handler because it handles an IndexOutOfBoundsException .
Hence, it is executed.
Catching Multiple Exceptions
From Java SE 7 and later, we can now catch more than one type of
exception with one catch block.
This reduces code duplication and increases code simplicity and efficiency.
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
}
To learn more, visit Java catching multiple exceptions.
Java try-with-resources statement
The try-with-resources statement is a try statement that has one or more
resource declarations.
Its syntax is:
try (resource declaration) {
// use of the resource
} catch (ExceptionType e1) {
// catch block
}
The resource is an object to be closed at the end of the program. It must be
declared and initialized in the try statement.
Let's take an example.
try (PrintWriter out = new PrintWriter(new FileWriter("OutputFile.txt")) {
// use of the resource
}
The try-with-resources statement is also referred to as automatic
resource management. This statement automatically closes all the
resources at the end of the statement.
To learn more, visit the java try-with-resources statement.
Java throw and throws
use throw and throws keyword for exception handling with the help of
examples. https://www.javatpoint.com/exception-handling-in-java
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are
three types of exceptions namely:
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
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.
In Java, exceptions can be categorized into two types:
Unchecked Exceptions: They are not checked at compile-time but
at run-time.For
example: ArithmeticException , NullPointerException , ArrayIndexOutOfBoundsExce
ption , exceptions under Error class, etc.
Checked Exceptions: They are checked at compile-time. For
example, IOException , InterruptedException , etc.
Refer to Java Exceptions to learn in detail about checked and unchecked
exceptions.
Usually, we don't need to handle unchecked exceptions. It's because
unchecked exceptions occur due to programming errors. And, it is a good
practice to correct them instead of handling them.
This tutorial will now focus on how to handle checked exceptions
using throw and throws .
Java throws keyword
We use the throws keyword in the method declaration to declare the type of
exceptions that might occur within it.
Its syntax is:
accessModifier returnType methodName() throws ExceptionType1, ExceptionType2 … {
// code
}
As you can see from the above syntax, we can use throws to declare
multiple exceptions.
Example 1: Java throws Keyword
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);
}
public static void main(String[] args) {
try{
findFile();
} catch(IOException e){
System.out.println(e);
}
}
}
Output
java.io.FileNotFoundException: test.txt (No such file or directory)
When we run this program, if the file test.txt does not
exist, FileInputStream throws a FileNotFoundException which extends
the IOException class.
If a method does not handle exceptions, the type of exceptions that may
occur within it must be specified in the throws clause so that methods further
up in the call stack can handle them or specify them using throws keyword
themselves.
The findFile() method specifies that an IOException can be thrown.
The main() method calls this method and handles the exception if it is
thrown.
Throwing multiple exceptions
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 {
// code that may produce NullPointerException
… … …
// code that may produce IOException
… … …
// code that may produce InvalidClassException
… … …
}
public static void main(String[] args) {
try{
findFile();
} catch(IOException e1){
System.out.println(e1.getMessage());
} catch(InvalidClassException e2){
System.out.println(e2.getMessage());
}
}
}
Here, the findFile() method specifies that it can
throw NullPointerException , IOException , and InvalidClassException in
its throws clause.
Note that we have not handled the NullPointerException . This is because it is
an unchecked exception. It is not necessary to specify it in the throws clause
and handle it.
throws keyword Vs. try...catch...finally
There might be several methods that can cause exceptions.
Writing try...catch for each method will be tedious and code becomes long
and less-readable.
throws is also useful when you have checked exception (an exception that
must be handled) that you don't want to catch in your current method.
Java throw keyword
The throw keyword is used to explicitly throw a single exception.
When an exception is thrown, the flow of program execution transfers from
the try block to the catch block. We use the throw keyword within a method.
Its syntax is:
throw throwableObject;
A throwable object is an instance of class Throwable or subclass of
the Throwable class.
Example 2: Java throw keyword
class Main {
public static void divideByZero() {
throw new ArithmeticException("Trying to divide by 0");
}
public static void main(String[] args) {
divideByZero();
}
}
Output
Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0
at Main.divideByZero(Main.java:3)
at Main.main(Main.java:7)
exit status 1
In this example, we are explicitly throwing an ArithmeticException.
Note: ArithmeticException is an unchecked exception. It's usually not
necessary to handle unchecked exceptions.
Example 3: Throwing checked exception
import java.io.*;
class Main {
public static void findFile() throws IOException {
throw new IOException("File not found");
}
public static void main(String[] args) {
try {
findFile();
System.out.println("Rest of code in try block");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Output
File not found
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");
}
}
Difference between throw and throws in Java
The throw and throws is the concept of exception handling where the throw keyword
throw the exception explicitly from a method or a block of code whereas the throws
keyword is used in signature of the method.
There are many differences between throw and throws keywords. A list of differences
between throw and throws are given below:
Sr. Basis of Differences throw throws
no.
1. Definition Java throw keyword is used Java throws keyword is used in
throw an exception explicitly in the method signature to declare
the code, inside the function or an exception which might be
the block of code. thrown by the function while the
execution of the code.
2. Type of exception Using throw Using throws keyword, we can
keyword, we can only propagate declare both checked and
unchecked exception i.e., the unchecked exceptions.
checked exception cannot be However, the throws keyword
propagated using throw only. can be used to propagate
checked exceptions only.
3. Syntax The throw keyword is followed The throws keyword is followed
by an instance of Exception to by class names of Exceptions to
be thrown. be thrown.
4. Declaration throw is used within the throws is used with the method
method. signature.
5. Internal implementation We are allowed to throw only We can declare multiple
one exception at a time i.e. we exceptions using throws
cannot throw multiple keyword that can be thrown by
exceptions. the method. For example, main()
throws IOException,
SQLException.
Java throw Example
TestThrow.java
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:
Competitive questions on Structures in Hindi
Keep Watching
Java throws Example
TestThrows.java
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:
Java throw and throws Example
TestThrowAndThrows.java
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.
Before Java 7, we had to write multiple exception handling codes for
different types of exceptions even if there was code redundancy.
Let’s take an example.
Example 1: Multiple catch blocks
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
In this example, two exceptions may occur:
ArithmeticException because we are trying to divide a number by 0.
ArrayIndexOutOfBoundsException because we have declared a new integer
array with array bounds 0 to 9 and we are trying to assign a value to
index 10.
We are printing out the exception message in both the catch blocks i.e.
duplicate code.
The associativity of the assignment operator = is right to left, so
an ArithmeticException is thrown first with the message / by zero .
Handle Multiple Exceptions in a catch Block
2. Write a java program that handles the following exceptions
using multiple catch blocks:
Arithmetic exception
ArrayIndexOutOfBoundsException
Exception
class Exception5{
public static void main(String args[]){
try{
int arr[]=new int[7];
arr[10]=10/5;
System.out.println("Last Statement of try block");
}
catch(ArithmeticException e){
System.out.println("You should not divide a number by zero");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Accessing array elements outside of the
limit");
In Java SE 7 and later, we can now catch more than one type of exception
in a single catch block.
Each exception type that can be handled by the catch block is separated
using a vertical bar or pipe | .
Its syntax is:
try {
// code
} catch (ExceptionType1 | Exceptiontype2 ex) {
// catch block
}
Example 2: Multi-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
Catching multiple exceptions in a single catch block reduces code
duplication and increases efficiency.
The bytecode generated while compiling this program will be smaller than
the program having multiple catch blocks as there is no code redundancy.
Note: If a catch block handles multiple exceptions, the catch parameter is
implicitly final . This means we cannot assign any values to catch
parameters.
Catching base Exception
When catching multiple exceptions in a single catch block, the rule is
generalized to specialized.
This means that if there is a hierarchy of exceptions in the catch block, we
can catch the base exception only instead of catching multiple specialized
exceptions.
Let’s take an example.
Example 3: Catching base exception class only
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
We know that all the exception classes are subclasses of
the Exception class. So, instead of catching multiple specialized exceptions,
we can simply catch the Exception class.
If the base exception class has already been specified in the catch block, do
not use child exception classes in the same catch block. Otherwise, we will
get a compilation error.
Let’s take an example.
Example 4: Catching base and child exception classes
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
Main.java:6: error: Alternatives in a multi-catch statement cannot be related by
subclassing
In this example, ArithmeticException and ArrayIndexOutOfBoundsException are both
subclasses of the Exception class. So, we get a compilation error.
https://www.programiz.com/java-programming/multiple-exceptions
Difference between final, finally and finalize
The final, finally, and finalize are keywords in Java that are used in exception
handling. Each of these keywords has a different functionality. The basic difference
between final, finally and finalize is that the final is an access modifier, finally is the
block in Exception Handling and finalize is the method of object class.
Sr. Key final finally finalize
no.
1. Definition final is the keyword and finally is the block in Java finalize is the method in
access modifier which is Exception Handling to Java which is used to
used to apply execute the important perform clean up
restrictions on a class, code whether the processing just before
method or variable. exception occurs or not. object is garbage
collected.
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.
4. Execution Final method is Finally block is executed finalize method is
executed only when we as soon as the try-catch executed just before the
call it. block is executed. object is destroyed.
It's execution is not
dependant on the
exception.
Along with this, there are many differences between final, finally and finalize. A list of
differences between final, finally and finalize are given below:
Java final Example
Let's consider the following example where we declare final variable age. Once
declared it cannot be modified.
FinalExampleTest.java
Hello Java Program for Beginners
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.
Java finally Example
Let's see the below example where the Java code throws an exception and the catch
block handles that exception. Later the finally block is executed after the try-catch
block. Further, the rest of the code is also executed normally.
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:
Java finalize Example
FinalizeExample.java
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