What is Exception?
Exception in Java is used to handle errors or any other
exceptional event that occurs in the normal flow of a program. There are
several way Exception can occur in Java.
Data provided is not in expected format(eg. int instead of
String).
DB cannot be connected.
Network connection Lost.
An object is null.
Exception hierarchy
Exception and Error are two different classes that derived
from Throwable.
Errors represent a situation which doesn’t occur because of
Programming error but that might happen at the time of program execution and
these are abnormal behavior which java program cannot handle and shouldn’t
bother to handle. JVM running out of memory is a type of Error which can occur
at runtime.
Object
Throwable
Exceptions Error
Checked
Exception Virtual
machine error
Unchecked Exception Stackoverflowerror Out of memory error
1) Checked Exception
IOException, SQLException etc
2) Unchecked Exception
ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc
3) Error
OutOfMemoryError, VirtualMachineError, AssertionError etc.
Checked vs UnChecked Exception
Checked
exceptions are subclass’s of Exception excluding RuntimeException and its
subclasses |
Unchecked
exceptions are RuntimeException and any of its subclasses. |
Checked
Exceptions force programmers to deal with the exception that may be thrown. |
A compiler
doesn’t force the programmers to either catch the unchecked exception or
declare it in a throws clause. Programmers
may not even know that the exception could be thrown |
When a
checked exception occurs in a method, the method must either catch the
exception and take the appropriate action,or pass the exception on to its
caller. |
Runtime
exceptions do not need to be. |
Checked
exceptions must be caught at compile time. |
Unchecked
exceptions must be caught at run time. |
Example IO exception. |
Example ArrayIndexOutOfBounds
Exception. |
What are the In built Exceptions in Java?
ArithmeticException
ArrayIndexOutOfBoundsException
ClassNotFoundException
FileNotFoundException
IOException
InterruptedException
NoSuchFieldException
NoSuchMethodException
NullPointerException
NumberFormatException
RuntimeException
StringIndexOutOfBoundsException
What is Exception Handling?
A mechanism to handle the runtime error.
Handling exception means transferring the execution of the
program to an appropriate handler when an exception occurs
Now we know that exception can occur in Java program at any
time(or Any Location). So we need to know how to handle these exceptions. Handling exception is a required attribute in
developing a robust application. Handling Exception means transferring
execution of the program to appropriate handler when an exception occurs. We
can handle the exception by using try-catch block.
try: try is used to define the block of code where an
exception can occur.
catch: catch is used to match a specific type of exception.
There could be more than one catch clause for one try block.
finally: finally determine a block of code which will always
execute after the try block. Even in the case of Exception.
try {
throw
new IOException();
}
catch (IOException e) {
//
Handle only IO Exception
//
This block will get executed only in case of IOException
}catch
(Exception e) {
//
Handle only all other type of exception
//
This block will get executed in case of all exception except IOException
}finally{
System.out.println("This
block will get executed no matter exception occur or not");
}
Error vs Exception
Error: An Error indicates
serious problem that a reasonable application should not try to catch.
Exception: Exception
indicates conditions that a reasonable application might try to catch.
Exception Propagation
It is not required to handle all exception thrown by try
block in the catch block (As it is not required block). In case catch block
doesn’t handle the exception thrown by try block, it will be propagated to the
method where this method was called from. In case the previous method which
called this method also doesn’t handle it, the exception will be propagated to
the last method in method stack, and it will keep propagating in the same way
unless some method handle it. In case none of the methods handle it in the call
stack, the exception will reach to bottom and JVM will handle it.
Java Keywords
TRY CATCH FINALLY THROW THROWS
TRY & CATCH
Java try block is used to
enclose the code that might throw an exception. It must be used within the
method.
If an exception occurs at the particular
statement of try block, the rest of the block code will not execute. So, it is
recommended not to keeping the code in try block that will not throw an
exception.
Java try block must be followed by either catch
or finally block.
package selenium;
public class Expectionhandling {
public
static void main(String[] args) {
//
TODO Auto-generated method stub
int
a;
a=100/0;
System.out.println(a);
System.out.println("Test");
}
}
Output
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at
selenium.Expectionhandling.main(Expectionhandling.java:8)
How to handle the exception using try catch block?
public static void main(String args[]){
try{
//code that may
raise exception
int
a=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the
program
System.out.println("rest
of the code...");
}
}
Output:
java.lang.ArithmeticException: / by zero
rest of the code...
Multiple catch
A try block can be followed by one or more catch blocks.
Each catch block must contain a different exception handler. So, if you have to
perform different tasks at the occurrence of different exceptions, use java
multi-catch block
At a time only one exception occurs and at a time only one
catch block is executed.
All catch blocks must be ordered from most specific to most
general, i.e. catch for ArithmeticException must come before catch for Exception.
public static void main(String[] args) {
try{
}
catch(Exception e)
{
}
catch(Exception e)
{
}
catch(Exception e)
{
}
System.out.println("rest of
the code");
}
Eg:
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
Nested Try
Sometimes a situation may
arise where a part of a block may cause one error and the entire block itself
may cause another error,
class classname{
public static void
main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new
int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception
e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}
Java finally block
To execute important code such as closing connection, stream
etc.
always executed whether exception is handled or not.
follows try or catch block
It is used to put "cleanup" code such as closing a
file, closing connection etc
3 sample cases to watch out the printing order when it handles
the exception and also when it doesn’t,
1.finally example where exception doesn't occur
public static void
main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always
executed");}
System.out.println("rest of the code...");
}
Output:5
finally block is
always executed
rest of the code...
2.finally example where exception occurs and not handled.
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException
e){System.out.println(e);}
finally{System.out.println("finally
block is always executed");}
System.out.println("rest of
the code...");
}
Output:
finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
3.finally example where exception occurs and handled.
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException
e){System.out.println("Its an
Arithmetic error");}
finally{System.out.println("finally
block is always executed");}
System.out.println("rest of
the code...");
}
Output:
Its an Arithmetic error
finally block is always executed
rest of the code...
THROW
The Java throw keyword is used to explicitly throw an
exception.
Useful to throw the customized error messages. Much useful
for the user defined exceptions.
public class TestThrow1{
static void
validate(int age){
if(age<18)
throw new
ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void
main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
THROWS
The Java throws keyword is used to declare an exception. It
gives an information to the programmer that there may occur an exception so it
is better for the programmer to provide the exception handling code so that
normal flow can be maintained.
return_type method_name() throws exception_class_name{
//method code
}
Eg:
void m()throws ArithmeticException{
throw new ArithmeticException("sorry error occured");
}
THROW |
THROWS |
Java throw
keyword is used to explicitly throw an exception |
Java throws
keyword is used to declare an exception |
Checked
exception cannot be propagated using throw only |
Checked
exception can be propagated with throws |
Throw is used
within the method |
Throws is
used with the method signature |
You cannot
throw multiple exceptions |
You can
declare multiple exceptions e.g. public void method()throws
IOException,SQLException |
User Defined Exceptions
If you are creating your own Exception that is known as
custom exception or user-defined exception. Java custom exceptions are used to
customize the exception according to user need.
By the help of custom exception, you can have your own
exception and message.
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class CustomException{
static void
validate(int age)throws InvalidAgeException{
if(age<18)
throw new
InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static
void main(String args[]){
try{
validate(13);
}catch(Exception
a){System.out.println("Exception occured: "+a);
}
System.out.println("rest of the
code...");
}
}
output:
Exception occured: InvalidAgeException: not valid
To Summarize:
The "try" keyword is used to specify a block where
we should place exception code. The try block must be followed by either catch
or finally. It means, we can't use try block alone.
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.
The "finally" block is used to execute the
important code of the program. It is executed whether an exception is handled
or not.
The "throw" keyword is used to throw an exception
The "throws" keyword is used to declare
exceptions. It doesn't throw an exception. It specifies that there may occur an
exception in the method. It is always used with method signature.
try {
throw
new IOException();
}
catch (IOException e) {
//
Handle only IO Exception
//
This block will get executed only in case of IOException
}catch
(Exception e) {
//
Handle only all other type of exception
//
This block will get executed in case of all exception except IOException
}finally{
System.out.println("This
block will get executed no matter exception occur or not");
}
No comments:
Post a Comment