ExceptionHandling
ExceptionHandling
—------------------
Q)What is the difference between Error and Exception?
—------------------------------------------------------
Ans:
—---
Error is a problem , it will not allow us to execute applications.
1. Compilation Errors
2. Runtime Errors
Compilation Errors:
—--------------
These errors are generated at compilation time.
There are three types of Compilation Errors.
1. Lexical Errors
2. Syntax Errors
3. Semantic Errors
Lexical Errors:
—----------
These errors are identified by the Lexical Analysis phase in
Compilation.
EX: Mistakes in the tokens
EX: int i = 10; —---> Valid
nit i = 10; —---> Invalid, Lexical Error
Syntax Errors:
—----------
These errors are identified in the Syntax Analysis phase in
Compilation.
EX: Mistakes in the syntaxes.
EX: int i = 10; —-> Valid
i 10 int; —---> Invalid, Syntax Error
EX: while(i < 10){
Sopln(i);
}
Status: Valid
Semantic Error:
—----------
These errors are identified in the Semantic Analysis phase in
compilation.
EX: Meaningless statements.
EX: Providing incompatible operands for the operators.
EX: int i = 10;
boolean b = true;
char c = i + b;
Note: Along with the above three types of errors, all the programming
languages are having their own errors as per the programming language
rules and regulations.
The errors which are identified at runtime and which are not having
solutions programmatically then these errors are “Runtime Error”.
Exception:
Exception is an unexpected event occurred at runtime of the
application, which may be provided by the users while entering dynamic
input to the java applications, which may be provided by the Databases
when we perform database operations from java applications in JDBC
applications, which may be provided by the network when we establish
connection between client and Server in Distributed
applications,....... Causes abnormal termination to the applications.
Predefined Exceptions:
—----------------------
These exceptions are defined by the Java programming languages , Java
has provided predefined classes for these exceptions in the Java
predefined library.
*************************************OR******************************
All the remaining Exceptions are the examples for Checked Exceptions.
If we run the above program then JVM will provide the following
exception message.
The above Exception message is divided into the following three parts.
1. Exception Name : java.lang.ArithmeticException
2. Exception Description : / by zero
3. Exception Location : Main.java: 5
2. NullPointerException:
—--------------------
If we access any instance variable or instance method on a reference
variable containing null value then JVM will raise
NullPointerException.
EX:
import java.util.Date;
If we run the above program then JVM will provide the following
exception details.
1. Exception Name: java.lang.NullPointerException
2. Exception Description : Cannot invoke "java.util.Date.toString()"
because
"date" is null
3. Exception Location: Main.java: 6
3. ArrayIndexOutOfBoundsException:
—------------------------------
In Java applications, when we access an element from an array on the
basis of the index value , when we insert an element in an array on
the basis of the index value, where the provided index value is in the
outside range of array indexes there JVM will raise
ArrayIndexoutOfBoundsException.
EX:
import java.util.Date;
4. StringIndexOutOfBoundsException:
—------------------------------
In Java applications , when we are performing String operations on the
basis of the index value , where the provided index value is in the
outside range of the String indexes there JVM will raise
StringIndexOutOfBoundsException .
EX:
import java.util.Date;
If we run the above program then JVM will provide the following
exception details.
5. ClassNotFoundException:
—----------------------
In Java applications, if we want to load a particular class bytecode
to the memory then we will use the Class.forName() method.
EX:
public class Main {
public static void main(String[] args) throws
Exception {
Class cls = Class.forName("Employee");
}
}
If we run the above program then JVM will provide the following
exception details.
*********************************OR*****************************
In Java applications, if we want to load a particular class byte code
to the memory without creating an object then we will use the
following method from java.lang.Class class.
When JVM encounter the above instruction, JVM will search for A.class
file at current location, at java predefined library and at the
locations referred by "classpath" environment variable, if the
required A.class file is not identified at all the locations then JVM
will rise ClassNotFoundException.
EX:
class A{
static
{
sop(“Class Loading”);
}
}
class Test{
psvm(String[] args) throws Exception{
Class c = Class.forName(“AAA”);
}
}
If we run this code the JVM will provide the following exception
details.
● Exception Name: java.lang.ClassNotFoundException
● Exception Description: AAA
● Exception Location: Test.java: 12
● InstantiationException
● IllegalArgumentException
In java applications, if we load class byte code by using
"Class.forName(-)" method then to create an object explicitly we have
to use the following method from java.lang.Class class.
When JVM encounters the above code then JVM will search for 0-arg
constructor and nonprivate constructor in the loaded class. if 0-arg
constructor is not available, if parameterized constructor is existed
then JVM will rise "java.lang.instantiationException". If non-private
constructor is not available, if private constructor is available then
JVM will raise "java.lang.IllegalAccessException".
class A{
static{
sop(“Class Loading…”);
}
A(int i){
sop(“Object Creating…”);
}
}
class Test{
psvm(String[] args)throws Exception{
Class c = Class.forName(“A”);
Object obj = c.newInstance();
}
}
If run the above code then JVM will provide an exception with the
following details.
● Exception Name : java.lang.InstantiationException
● Exception Description: A
● Exception Location:Test.java: 17
EX:
class A{
static{
sop(“Class Loading…”);
}
private A(){
sop(“Object Creating…”);
}
}
class Test{
psvm(String[] args)throws Exception{
Class c = Class.forName(“A”);
Object obj = c.newInstance();
}
}
If we run the above code then JVM will raise an exception with the
following details.
● Exception Name : java.lang.IllegalAccessException
● Exception Description: Test class cannot access the members of
class A with the modifier "private".
● Exception Location" Test.java: 17
*************************************END***************************
6. InstantiationException:
—----------------------
In Java applications, by using Class.forName() method we are able to
load a particular class bytecode to the memory, after loading class
bytecode if we want to create an object for the loaded class we have
to use the following method java.lang.Class.
EX:
class Employee{
Employee(int i){
System.out.println("Employee-Constructor");
}
}
public class Main {
public static void main(String[] args) throws
Exception {
Class cls = Class.forName("Employee");
Employee employee = (Employee) cls.newInstance();
}
}
If we run the above program then JVM will provide the following
details
1. Exception Name: java.lang.InstantiationException
2. Exception Description : Employee
3. Exception Location : Main.java: 9
7. IllegalAccessException:
—----------------------
In Java applications, by using Class.forName() method we are able to
load a particular class bytecode to the memory, after loading class
bytecode if we want to create an object for the loaded class then we
have to use the following method from java.lang.Class.
If we execute the above instruction, JVM will search for a non private
constructor in the Employee class. If we have a private constructor in
the Employee class then JVM will raise IllegalAccessException .
EX:
class Employee{
private Employee(){
System.out.println("Employee-Constructor");
}
}
public class Main {
public static void main(String[] args) throws
Exception {
Class cls = Class.forName("Employee");
Employee employee = (Employee) cls.newInstance();
}
}
If we run the above code then JVM will provide the following exception
details.
8. ClassCastException:
—------------------
In Java applications, we are able to keep subclass object reference
value in superclass reference variable, but we are unable to keep
superclass object reference value in subclass reference variable, if
we keep superclass object reference value in subclass reference
variable then JVM will raise ClassCastException.
EX:
class Employee{
}
class Manager extends Employee{
}
public class Main {
public static void main(String[] args) throws
Exception {
Employee employee = new Employee();
Manager manager = (Manager) employee;
}
}
If we run the above program then JVM will provide the following
Exception details.
1. Exception Name : java.lang.ClassCastException:
2. Exception Description : class Employee cannot be cast to class
Manager
3. Exception Location : Main.java: 10
9. FileNotFoundException:
—---------------------
In Java applications, when we are trying to read data by using
FileInputStream or FileReader from a particular file and if the
provided file is not available then JVM will raise
FileNotFoundException.
EX:
import java.io.FileInputStream;
If we run the above code then JVM will provide the following exception
details.
‘throw’ Keyword:
—-----------------
‘throw’ is a Java keyword, it can be used to raise or generate an
exception intentionally as per the application requirement.
EX:
Student.java
package com.durgasoft.entities;
Main.java
import com.durgasoft.entities.Student;
Note:
If we provide any statement immediately after the throw statement then
the compiler will raise an error like Unreachable Statement.
‘throws’ keyword:
—-----------------
‘throws’ is a Java keyword, it can be used to bypass the generated
exception from the present method to the caller method in order to
handle that exception.
EX:
void m1()throws Exception1, Exception2,... Exception_n{
—------
}
EX:
void m1()throws RuntimeException{
throw new ArithmeticException();
}
Status: Valid
EX:
void m1()throws FileNotFoundException{
throw new IOException();
}
Status: Invalid
EX:
void m1() throws NullPointerException, ClassNotFoundException{
}
Status: Valid
EX:
void m1()throws IOException, FileNotFoundException{
}
Status: Valid, Not suggestible
EX:
void m1() throws Exception{
……………
……………
}
void m2(){
try{
m1();
}catch(Exception e){
e.printStackTrace();
}
}
EX:
void m1() throws Exception{
…………
}
void m2() throws Exception{
m1();
}
EX:
—--
import java.io.*;
class A{
void add(){
concat();
}
void concat(){
throw new IOException("My IO Exception");
}
}
class Test{
public static void main(String[] args){
A a = new A();
a.add();
}
}
D:\java6>javac Test.java
Test.java:7: error: unreported exception IOException; must be caught
or declared to be thrown
throw new IOException("My IO Exception");
^
1 error
D:\java6>
EX:
import java.io.*;
class A{
void add(){
concat();
}
void concat()throws IOException {
throw new IOException("My IO Exception");
}
}
class Test{
public static void main(String[] args){
A a = new A();
a.add();
}
}
D:\java6>javac Test.java
Test.java:4: error: unreported exception IOException; must be caught
or declared to be thrown
concat();
^
1 error
D:\java6>
EX:
import java.io.*;
class A{
void add()throws Exception{
concat();
}
void concat()throws IOException {
throw new IOException("My IO Excxeption");
}
}
class Test{
public static void main(String[] args){
A a = new A();
a.add();
}
}
D:\java6>javac Test.java
Test.java:13: error: unreported exception Exception; must be caught or
declared to be thrown
a.add();
^
1 error
D:\java6>
EX:
import java.io.*;
class A{
void add()throws Exception{
concat();// IOException
}
void concat()throws IOException {
throw new IOException("My IO Excxeption");
}
}
class Test{
public static void main(String[] args)throws Throwable{
A a = new A();
a.add();// Exception
}
}
D:\java6>javac Test.java
D:\java6>java Test
Exception in thread "main" java.io.IOException: My IO Excxeption
at A.concat(Test.java:7)
at A.add(Test.java:4)
at Test.main(Test.java:13)
D:\java6>
Internal Flow:
—-----------
If we execute the above program, then JVM will recognize throws
keyword in concat() method and JVM will rise an exception in concat()
method, due to throws keyword in concat() method prototype, Exception
will be bypassed to concat() method call that is in add(), due to
throws keyword in add() method, Exception will be passed to add()
method caller, that is, in main() method call, that is, to JVM, where
JVM will activate “Default Exception Handler”, where Default Exception
Handler will display exception details.
Q)What are the differences between throw keyword and throws keyword?
—--------------------------------------------------------------------
Ans:
—----
1. throw keyword can be used to raise an exception intentionally as
per the application requirement.
2. In general, we will use the throw keyword inside the method body.
try-catch-finally:
—-----------------
In Java applications, throws keyword is not handling the exceptions
really, it is able to bypass the generated exception from the present
method to the caller method in order to handle exceptions.
Syntax:
try{
—----Instructions—---
}catch(ExceptionName refVar){
—---Instructions—----
}finally{
—----Instructions—----
}
try block:
—----------
1. It will include the doubtful code where exceptions may or may not
be generated.
2. If we have any exception in the try block then JVM will bypass
flow of execution to the catch block by passing the generated
exception object as parameter to the catch block and by skipping
the remaining instructions after the exception in the try block.
3. If no exception is identified in try block then JVM will execute
try block completely, at the end of the try block JVM will bypass
flow of execution to the finally block by skipping catch block.
EX:
public class Main {
public static void main(String[] args) {
System.out.println("Before try block");
try{
System.out.println("Inside try block, before
Exception");
float f = 100/0;
System.out.println("Inside try block, After
Exception");
}catch(Exception e){
System.out.println("Inside catch block");
}finally{
System.out.println("Inside finally block");
}
System.out.println("After finally block");
}
}
EX:
public class Main {
public static void main(String[] args) {
System.out.println("Before try block");
try{
System.out.println("Inside try block");
}catch(Exception e){
System.out.println("Inside catch block");
}finally{
System.out.println("Inside finally block");
}
System.out.println("After finally block");
}
}
catch block:
—------------
In try-catch-finally syntax, when we have an exception in try block
the JVM will execute catch block.
The main purpose of catch block is to catch the exception from try
block and to display the generated exception details on console.
2. By using System.out.println(e):
—------------------------------------
When we pass Exception object reference variable as parameter to
System.out.println() method , JVM will execute toString() method
internally , where in Exception classes Object class provided
toString() method was overridden in such a way that to return a string
that contains the exception details like name of the exception and
description of the exception.
EX:
public class Main {
public static void main(String[] args) {
try{
float f = 100/0;
}catch(Exception e){
e.printStackTrace();
System.out.println();
System.out.println(e);
System.out.println();
System.out.println(e.getMessage());
}finally{
}
}
}
OP:
java.lang.ArithmeticException: / by zero
at Main.main(Main.java:4)
java.lang.ArithmeticException: / by zero
/ by zero
finally block:
—-------------
Finally block is able to include a set of instructions which must be
executed by JVM irrespective of having exceptions in try block and
irrespective of executing catch block.
a.) final variable: It will not allow modifications over its value.
b) final methods: It will not allow method overriding.
c)final class: It will not allow inheritance, that is, sub classes.
finally block:
—-----------
It is part of try-catch-finally syntax, it will include some
instructions, which must be executed by JVM irrespective of getting
exception from try block and irrespective of executing catch block.
finalize():
—-------
It is a method in java.lang.Object class, it will be executed just
before destroying objects in order to give final notification to the
user about to destroy objects.
OP:
30
EX:
class A{
int m1(){
try{
float f = 100/0;
return 10;
}catch(Exception e){
return 20;
}finally{
return 30;
}
}
}
public class Main {
public static void main(String[] args) {
A a = new A();
System.out.println(a.m1());
}
}
OP:
30
try{
}finally{
}
In the above context, if we have any exception then JVM will execute
both try and finally blocks then JVM will display the generated
exception details.
EX:
OP:
Inside try block, before exception
Inside finally block
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:6)
REASON: When JVM encounter exception in try Block, JVM will search for
catch Block, if no catch block is identified, then JVM will terminate
the program abnormally after executing the finally block.
try{
}catch(Exception e){
}
EX:
try{
}catch(Exception e){
try{
}catch(Exception e1){
}finally{
}
}finally{
}
EX:
try{
}catch(Exception e){
}finally{
try{
}catch(Exception e){
}finally{
}
}
EX:
import java.util.Date;
OP:
Before try block
Inside try, before nested try
Inside try, inside nested try
Inside try, inside nested finally
Inside try, after nested finally
Inside catch, inside nested try
Inside catch, inside nested catch
Inside catch, inside nested finally
Inside catch, after nested finally
Inside finally, inside nested try
Inside finally, inside nested finally
Inside finally, after nested finally
After finally
1. We can write multiple catch blocks with the Exception class names
, but if these Exception classes are having inheritance relation
then we must provide all the catch blocks as per the exception
classes' inheritance increasing order. If Exception classes are
not having inheritance relation then it is possible to provide
all catch blocks in any order.
2. If any catch block has a pure checked exception then the
respective try block must raise the same pure checked exception.
EX1:
try{
—---
}catch(ArithmeticException e){
}catch(NullPointerException e){
}catch(ArrayIndexOutOfBoundsException e){
}
Status: Valid
EX2:
try{
—---
}catch(NullPointerException e){
}catch(ArithmeticException e){
}catch(ArrayIndexOutOfBoundsException e){
}
Status: Valid
EX2:
try{
—---
}catch(ArithmeticException e){
}catch(RuntimeException e){
}catch(Exception e){
}
Status: Valid
EX2:
try{
—---
}catch(Exception e){
}catch(RuntimeException e){
}catch(ArithmeticException e){
}
Status: Invalid
EX:
try{
throw new IOException();
}catch(ArithmeticException e){
}catch(IOException e){
}catch(NullPointerException e){
}
Status: Valid
EX:
try{
throw new ArithmeticException();
}catch(ArithmeticException e){
}catch(IOException e){
}catch(NullPointerException e){
}
Status: Invalid
EX:
public class InsufficientFundsException extends Exception{
public InsufficientFundsException(String exceptionDescription){
super(exceptionDescription);
}
}
EX:
try{
throw new InsufficientFundsException(“Funds Are Not Sufficient in
your
Account”);
}catch(InsufficientFundsException e){
e.printStacktrace();
}
EX:
—--
InsufficientFundsException.java
package com.durgasoft.exceptions;
Account.java
package com.durgasoft.entities;
Transaction.java
package com.durgasoft.entities;
import com.durgasoft.exceptions.InsufficientFundsException;
Main.java
import com.durgasoft.entities.Account;
import com.durgasoft.entities.Transaction;
import java.io.IOException;
}
}
}catch(Exception e){
}
Syntax:
try{
}catch(Exception-1 | Exception-2 | ……. | Exception-n e){
}
EX:
import java.util.Date;
EX:
import java.util.Date;
try-with-resources:
—------------------
In general, in java applications, we may use a number of resources
like Streams, database Connections, Network Connections,......
With the above approach, we are able to get the following problems.
1. We must close the resources explicitly, which may not be
guaranteed.
2. Providing try-catch-finally inside the finally block is somewhat
confusing.
Syntax:
try(Resource-1; Resource-2;...... Resource-n;){
}catch(Exception e){
}
EX:
try(
FileInputSteam fis = new FileInputStream(“abc.txt”);
Connection con = DriverManager.getConnection(“--”,”--”,”--”);
URLConnection uc = socket.openConnection();
){
—---
—----
}catch(Exception e){
e.printStackTrace();
}
==================================OR======================================
try-With-Resources/Auto Closeable Resources:
—---------------------------------------
In general, in Java applications, we may use the resources like Files,
Streams, Database Connections....as per the application requirements.
Syntax:
—----
try(Resource1; Resource2;........Resource-n){
-------
------
}catch(Exception e){
-----
-----
}
Where all the specified Resources classes or interfaces must implement
"java.io.AutoCloseable" interface.
Where if we declare resources as AutoCloseable resources along with
"try" then the resources reference variables are converted as "final"
variables.
try(File f = new File("abc.txt");
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
Connection con =
DriverManager.getConnection("jdbc:odbc:nag","system","durga ");)
{
—------
—------
}catch(Exception e) {
e.printStackTrace();
}