Exception Handling in Java With Examples (1)
Exception Handling in Java With Examples (1)
1. What is an Error?
2. Compile Time and Run time Errors
3. What is an Exception?
4. Why an exception occurs?
5. What happens when an exception is raised in the program?
6. What JVM does do when a logical mistake occurred in the
program?
7. Exception Hierarchy in Java
8. What are the differences between Error and Exception?
9. Types of Exceptions in Java
10.Checked and Unchecked Exceptions in Java
11.What is exception handling in Java?
12.Why do we need Exception Handling in Java?
13.How can we handle an exception in Java?
14.Multiple catch blocks in Java
15.Can we catch all exceptions using a single catch block?
16.When should we write multiple catch blocks for a single try
block?
17.How to display Exception or Runtime Error Message?
What is an Error?
An Error indicates a serious problem that a reasonable application should not
try to catch.
We have the following two types of errors:
These errors occurred when we enter the wrong data into a variable, try to
open a file for which there is no permission, try to connect to the database
with the wrong user id and password, the wrong implementation of logic,
missing required resources, etc.
There can be several reasons that can cause a program to throw an exception.
For example: Opening a non-existing file in your program, Network connection
problem, bad input data provided by the user, etc.
Why do we need Exception?
Suppose you have coded a program to access the server. Things worked fine
while you were developing the code.
During the actual production run, the server is down. When your program tried
to access it, an exception is raised.
How to Handle Exception
So far we have seen, exception is beyond developer’s control. But blaming your
code failure on environmental issues is not a solution. You need a Robust
Programming, which takes care of exceptional situations. Such code is known
as Exception Handler.
In our example, good exception handling would be, when the server is down,
connect to the backup server.
To implement this, enter your code to connect to the server (Using traditional if
and else conditions).
You will check if the server is down. If yes, write the code to connect to the
backup server.
Such organization of code, using “if” and “else” loop is not effective when your
code has multiple java exceptions to handle.
class connect{
if(Server Up){
// code to connect to server
}
else{
// code to connect to BACKUP server
}
}
It creates an exception class object that is associated with that logical mistake
and terminates the current method execution by throwing this exception
object by using the “throw” keyword.
After printing the value of a and b, JVM terminates this program execution by
throwing ArithmeticException because the logical mistake we committed is
dividing integer numbers by integer zero.
The java.lang.Throwable class is the root class of the Java Exception hierarchy
which is inherited by two subclasses:
Exception and Error.
All exception and error types are subclasses of class Throwable, which is the
base class of the hierarchy.
One branch is headed by Exception. This class is used for exceptional conditions
that user programs should catch.
NullPointerException is an example of such an exception.
Another branch, Error is used by the Java run-time system(JVM) to indicate
errors having to do with the run-time environment itself(JRE).
StackOverflowError is an example of such an error.
Here,
Object: Object is the super most class of all classes available in java.
Throwable: For all types of exceptions java.lang.Throwable is the superclass.
It has two main subclasses
1. Error
2. Exception
Exception: Exception is the super most class of all exceptions that may occur
because of programmer logic failure. These exceptions we can handle.
Error: Error is the super-most class of all exceptions that occur because of JVM
failure. These errors we cannot handle.
Difference 1:
Error type exception is thrown due to the problem that occurred inside JVM
logic, like If there is no memory in the java stack area to create a new
Stackframe to execute method then the JVM process is killed by throwing Error
type exception “java.lang.StackOverfolwError”.
If there is no memory in the heap area to create a new object then the JVM
process is killed by throwing the Error type exception
“java.lang.OutOfMemoryError”.
Exception type exceptions are thrown due to the problem that occurred in java
program logic, like If we divide an integer number with zero, then JVM
terminates program execution by throwing Exception type exception
“java.lang.ArithmeticException”.
If we pass the array size as a negative number, then JVM terminates the
program execution by throwing the exception type exception
“java.lang.NegativeArraySizeException”.
Difference 2:
We cannot catch an Error type exception because an error type exception is not
thrown in our application and once this error type exception is thrown JVM is
terminated.
We can catch an Exception type exception because an exception type exception
is thrown in our program and moreover JVM is not directly terminated because
of an exception type exception. JVM is only terminated if the thrown exception
is not caught.
Types of Exceptions in Java:
Example:
IOException,
ClassNotFoundException,
CloneNotSupportedException, etc.
These are the exceptions that are checked at compile time. If some code within
a method throws a checked exception, then the method must either handle
the exception or it must specify the exception using the throws keyword.
In checked exceptions, there are two types: fully checked and partially checked
exceptions. A fully checked exception is a checked exception where all its child
classes are also checked, like IOException, and InterruptedException. A partially
checked exception is a checked exception where some of its child classes are
unchecked, like an Exception.
For example, consider the following Java program that opens the file at location
“C:\test\a.txt” and prints the first three lines of it.
The program doesn’t compile, because the function main() uses FileReader(),
and FileReader() throws a checked exception FileNotFoundException. It also
uses readLine() and close() methods, and these methods also throw checked
exception IOException
package checkedunchecked;
import java.io.FileReader;
public class Checkedunchecked
{
public static void main(String[] args)
{
ClassA a1 = new ClassA();
a1.f1();
FileReader file = new FileReader("somefile.txt");
}
These are the exceptions that are not checked at compile time. In C++, all
exceptions are unchecked, so it is not forced by the compiler’s to either handle
or specify the exception. It is up to the programmers to be civilized and specify
or catch the exceptions.
Output:
The process of catching the exception for converting JVM given exception
message to end-user understandable message or for stopping the abnormal
termination of the program is called exception handling.
1. Logical implementation
2. Try catch implementation
import java.io.*;
public class Main
{
public static void main (String[]args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int a, b, c;
System.out.println("Enter Any 2 Numbers");
a = Integer.parseInt(br.readLine());
b = Integer.parseInt(br.readLine());
if (b == 0)
{
System.out.println("second number should not be zero");
}
else
{
c = a / b;
System.out.println("C VALUE = " + c);
}
}
}
Output:
In the above example when we entered the second number is zero, then the
exception will be raised and that is handled using logical implementation.
But while we are entering two numbers instead of the number if we entered
any character then it will give you one exception which is FormatException
which is not handled in this program as shown in the below image.
Whenever an exception has occurred within the particular method then the
corresponding exception object is created by the particular method and given
to JVM, then JVM will search for exception handling code within the particular
method if not available it will search in its caller method even there also it is
not available, then finally JVM will call “Default Exception Handler” Program
which will display the Exception object and terminate the method from java
stack (abnormal termination). In order to handle such a type of exception, we
need to go for Try catch implementation.
Exception handling in Java using the Try Catch implementation with
Examples
Try block:
try keyword establishes a block in which we need to write the exception
causing and its related statements. That means exception-causing statements
must be placed in the try block so that we can handle and catch that exception
for stopping abnormal termination and to display end-user understandable
messages.
Catch block:
The catch block is used to catch the exception that is thrown from its
corresponding try block. It has logic to take necessary on that caught exception.
Catch block syntax is look like a constructor. It does not take accessibility
modifier, normal modifier, or return type.
It takes a single parameter of type Throwable or its subclasses. Throwable is
the superclass of all exception sub-classes. Inside the catch block, we can write
any statement which is legal in java including raising an exception. A try block
can be followed by multiple catch blocks.
It is possible in Java to write multiple catch blocks for a single try block. Check
the below program.
import java.io.*;
public class Main
{
public static void main (String[]args) throws IOException
{
try
{
BufferedReader br = new BufferedReader (new InputStreamReader
(System.in));
int a, b, c;
System.out.println ("Enter Any 2 Numbers");
a = Integer.parseInt (br.readLine ());
b = Integer.parseInt (br.readLine ());
c = a / b;
System.out.println ("C VALUE = " + c);
}
catch (NumberFormatException nfe)
{
System.out.println ("please pass only integer values");
}
catch (ArithmeticException ae)
{
System.out.println ("please dont pass the second value as 0");
}
}
}
Output:
Note: After the try block, we can write multiple catch blocks to catch every
exception thrown from its corresponding try block.
We should write multiple catch blocks for a single try block because of the
following reasons
1. To print a message specific to an exception or
2. To execute some logic specific to an exception
In our multiple catch block programs, we have placed catch blocks with
different exception classes to print messages relevant to the caught exception.
Rules for Writing Multiple catch block in java:
Note: we write multiple catch blocks not only for printing exception-specific
messages but also for executing some logic specific to the exception raised in
the corresponding try statement.
Example: using multiple catch blocks along with generic catch block
import java.io.*;
public class Main
{
public static void main (String[]args) throws IOException
{
try
{
BufferedReader br = new BufferedReader (new InputStreamReader
(System.in));
int a, b, c;
System.out.println ("Enter Any 2 Numbers");
a = Integer.parseInt (br.readLine ());
b = Integer.parseInt (br.readLine ());
c = a / b;
System.out.println ("C VALUE = " + c);
}
catch (NumberFormatException nfe)
{
System.out.println ("please pass only integer values");
}
catch (ArithmeticException ae)
{
System.out.println ("please dont pass the second value as 0");
}
catch (Exception ex)
{
System.out.println ("Generic Exception");
}
}
}
Output:
Using toString():
If we use the toString() method it will display the reason why the Exception has
occurred and the Exception class name.
Using getMessage():
If we use the getMessage() method it will display only the reason why the
Exception has occurred.
//by using above statement we are just re-throwing the caught exception this
//exception is caught by JVM default handler and prints full exception
messages
//along with thread name
}
}
}
Output:
Java Exception Keywords
Java provides five keywords that are used to handle the exception. The
following table describes each.
Keyword Description