Exception Handling
Exception Handling
com/register/2348474801872643416
Exception Handling:
—------------------
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
(i < 10) while{
Sopln(i);
i = i + 1;
}
Status: Invalid, Syntax Error.
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:
These are runtime errors identified at runtime and which are having solutions
programmatically.
EX: ArithmeticException
EX: NullPointerException
EX: FileNotFoundException
—----------------------------------------------------------------------------
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.
Note: Really exceptions occur at runtime only, not at compilation time, but
Compiler can recognize some exceptions which are going to generate at runtime
then that exceptions are called “Checked Exceptions”.
If any exception is identified by the JVM at runtime , not by the compiler at
compilation time then that Exception is called “Unchecked Exception”.
2. RuntimeException and its subclasses, Error and its subclasses are the
examples for Unchecked Exceptions.
All the remaining Exceptions are the examples for Checked Exceptions.
If we run the above program then JVM will provide the following exception
message.
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.
JVM will search for Employee.class at the current location, at the predefined
library and at the locations referred by the classpath environment variable.
If the required Employee.class file is not available at all the above
locations then JVM will raise a ClassNotFoundException.
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.
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.
If we execute the above instruction, JVM will search for a 0-arg constructor
in the Employee class. If no 0-arg constructor is available in the Employee
class then JVM will raise InstantiationException .
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;
‘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:
—--
import java.io.*;
class A{
void add(){
concat();
}
void concat(){
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:7: error: unreported exception IOException; must be caught or
declared to be thrown
throw new IOException("My IO Excxeption");
^
1 error
D:\java6>
EX:
import java.io.*;
class A{
void add(){
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: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>
Q)What are the differences between throw keyword and throws keyword?
—--------------------------------------------------------------------
Ans:
—----
1. throw keyword can be used to raise an exception as per the application
requirement.
throws keyword can be used to bypass the generated exception from the
present method to the caller method.
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.
In java applications, we want to handle the exception right from the location
where it is generated , for this we have to use “try-catch-finally”.
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");
}
}
}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.
To display the exception details on the console we have to use the following
three approaches.
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.
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)
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
Q) Is it possible to provide more than one catch block for a single try
block?
—----------------------------------------------------------------------------
Ans:
—---
Yes, it is possible to provide more than one catch block for a single try
block with the following conditions.
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;
}
}
JAVA 7 features in Exception Handling:
—--------------------------------------
1. Multi-Catch Block
2. Try-with-resources
Multi-Catch Block:
—------------------
In the Multi-Catch block, we are able to handle multiple exceptions by using
a single catch block.
Syntax:
try{
}catch(Exception-1 | Exception-2 | ……. | Exception-n e){
}
The above catch block is able to catch any of the specified exceptions.
In the Multi-Catch block, all the provided exception classes must not have
inheritance relation, if inheritance relation is available between exception
classes then the compiler will raise an error.
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();
}
========================================================================