Exception Handling in Java
Exception Handling in Java
Exception is an event
that interrupts the normal flow of execution. It is a disruption during the
execution of the Java program.
A Java Exception is an
object that describes the exception that occurs in a program. When an
exceptional event occurs in java, an exception is said to be thrown. The code
that's responsible for doing something about the exception is called an exception
handler.
Exception Handling is
the mechanism to handle runtime malfunctions. We need to handle such exceptions
to prevent abrupt termination of program. The term exception means exceptional
condition, it is a problem that may arise during the execution of program. A
bunch of things can lead to exceptions, including programmer error, hardware
failures, files that need to be opened cannot be found, resource exhaustion
etc.
There are two types of errors:
- Compile
time errors
- Runtime
errors
Compile time errors can be again classified again into two
types:
- Syntax
Errors
- Semantic Errors
Instead of
declaring int
a; you mistakenly
declared it as in
a; for which
compiler will throw an error. Example: You have
declared a variable int
a; and after some
lines of code you again declare an integer as int a;. All these errors are highlighted when you
compile the code.
Runtime Errors Example
·
Exceptions in Java are
something that is out of developer’s control.
Exception class
Hierarchy
All exception types are
subclasses of class Throwable, which is at the top of exception
class hierarchy.
·
Exception class is for exceptional conditions that
program should catch. This class is extended to create user specific exception
classes.
·
RuntimeException is a subclass of Exception. Exceptions
under this class are automatically defined for programs.
·
Exceptions of type Error are used by
the Java run-time system to indicate errors having to do with the run-time
environment, itself. Stack overflow is an example of such an error.
Exceptions are
categorized into 3 categories.
·
Checked
Exception
The exception that can be predicted by the
programmer at the compile time.Example : File that need to be
opened is not found. These type of exceptions must be checked at compile time.
·
Unchecked
Exception
Unchecked exceptions are the class that extends
RuntimeException. Unchecked exceptions are ignored at compile time. Example: ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundException. Unchecked exceptions are
checked at runtime.
·
Error
Errors are typically ignored in code because you
can rarely do anything about an error. Example: if stack overflow
occurs, an error will arise. This type of error cannot be handled in the code.
Uncaught Exceptions
When we don't handle the
exceptions, they lead to unexpected program termination. Lets take an example
for better understanding.
class JavaException {
public static void
main(String args[]){
int a = 0;
int b = 20;
int c = a/b;
System.out.println("End Of Main");
}
}
This will lead to an
exception at runtime; hence the Java run-time system will construct an
exception and then throw it. As we don't have any mechanism for handling
exception in the above program, hence the default handler will handle the
exception and will print the details of the exception on the terminal.
Try
Catch Block
Java
provides an inbuilt exceptional handling.
- The normal code goes into a TRY block.
- The exception handling code goes
into the CATCH block
Syntax for using try & catch
try{
statement(s)
}
catch (exceptiontype
name){
statement(s)
}
class JavaException {
public static void main(String args[]) {
int a = 0;
int b = 20;
try {
int c = a / b;
System.out.println("This line will not
be Executed");
} catch (ArithmeticException e) {
System.out.println("In the catch Block
due to Exception = " + e);
}
System.out.println("End Of Main");
}
}
Nesting of try and catch blocks
Example: To understand nesting of try and catch
blocks
class JavaException {
public static void main(String args[]) {
try {
int a = 1;
int b = 20;
int c = a / b;
int g[] = { 1, 2, 3 };
g[20] = 100;
}
/*catch(Exception e){
System.out.println("In
the catch clock due to Exception = "+e);
}*/
catch (ArithmeticException e) {
System.out.println("In the catch clock
due to Exception = " + e);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("In the catch clock
due to Exception = " + e);
}
System.out.println("End Of Main");
}
}
Example 2:
class Excep
{
public static void main(String[] args)
{
try
{
int arr[]={5,0,1,2};
try
{
int x=arr[3]/arr[1];
}
catch(ArithmeticException ae)
{
System.out.println("divide by zero");
}
arr[5]=3;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“array index out of bound exception”);
}
}
}
Java
Finally Block
The
finally block is executed irrespective of an exception being
raised in the try block. It is optional to
use with a try block.
try {
statement(s)
} catch (ExceptiontType name) {
statement(s)
} finally {
statement(s)
}
In
case, an exception is raised in the try block, finally block is executed after
the catch block is executed.
How to
Create User Defined Exception in Java?
What
is User Defined Exception in Java?
User
Defined Exception or custom exception is creating your own exception class and
throws that exception using ‘throw’ keyword. This can be done by extending the
class Exception.
Example: To create a User-Defined Exception Class
class MyException extends Exception{
int a;
MyException(int b) {
a=b;
}
public String
toString(){
return
("Exception Number = "+a) ;
}
}
class JavaException{
public static void
main(String args[]){
try{
throw new
MyException(2);
// throw is used to
create a new exception and throw it.
}
catch(MyException e){
System.out.println(e)
;
}
}
}
Java throws Exception Syntax
method (Arguments) throws Exception1,Exception2,Exception,… {}
If you do not handle the exception in a
try catch block, compiling will fail. But almost every other method in the java
library or even user defined may throw an exception or two.
Handling all the exceptions using the try and
catch block could be cumbersome and will hinder the coder's throughput.
So java provides an option, wherein whenever you are using a
risky piece of code in the method definition you declare it throws an
exception without implementing try catch.
Java throws Example
import
java.io.*;
class
file1
{
public static void main(String[] args)
{
try
{
FileWriter file = new
FileWriter("c:\\Data1.txt");
file.write("Piyush");
file.close();
}
catch(IOException e){}
}
}
OR
import
java.io.*;
class
file1
{
public static void main(String[] args)
throws IOException
{
FileWriter file = new
FileWriter("c:\\Data1.txt");
file.write("Piyush");
file.close();
}
}
What is the difference between throw and
throws?
throw
|
throws
|
It is used to create a new Exception object and throw it
|
It is used in method definition, to declare that a risky
method is being called.
|
Using throw keyword you can declare only one Exception at a
time
|
Using throws keyword you can declare multiple exception at a
time.
|
Example:
throw new IOException("cannot open connection");
|
Example:
throws IOException, ArrayIndexBoundException;
|
Comments
Post a Comment