Java Exception Handling For Certification Interviews
Java Exception Handling For Certification Interviews
For
Certification
&
Interviews
1 https://www.youtube.com/durgasoftware
OCJA
Exception Handling
1) Introduction
4) Exception Hierarchy
9) finally Block
2 https://www.youtube.com/durgasoftware
OCJA
Introduction
An Unwanted Unexpected Event that Disturbs Normal Flow of the Program is Called
Exception.
Eg: SleepingException, TyrePuncheredException, FileNotFoundException Etc…
Exception Handling:
try {
//Read Data from Remote File locating at London
}
catch (FileNotFoundException e) {
//Use Local File and Continue Rest of the Program Normally
}
Q) What is an Exception?
Q) What is the Purpose of Exception Handling?
Q) What is the Meaning of Exception Handling?
3 https://www.youtube.com/durgasoftware
OCJA
class Test {
public static void main(String[] args) {
doStuff();
}
public static void doStuff() {
doMoreStuff();
}
public static void doMoreStuff() {
System.out.println("Hello"); //Hello
}
}
doMoreStuff()
doStuff( doStuff() doStuff(
)) ) main()
main() main() main() main()
Runtime Activation Record
Stack OR The Empty Stack
Stack Frame will be destroyed
by JVM
In Our Java Program Inside a Method if an Exception raised, then that Method is
Responsible to Create an Exception Object by including the following Information.
Name of Exception
Description of Exception
Location of Exception (Stack Trace)
After creating Exception Object Method Handovers that Object to the JVM.
JVM will Check whether Corresponding Method contain any Exception Handling
Code OR Not.
If the Method doesn't contain any Exception Handling Code then JVM Terminates
that Method Abnormally and Removes Corresponding Entry from the Stack.
JVM will Identify Caller Method and Check whether the Caller Method contain any
Exception Handle Code OR Not.
If Caller Method doesn't contain any Exception Handling Code then JVM Terminates
that Caller Method and Removes Corresponding Entry from the Stack.
This Process will be continued until main().
If the main() also doesn't contain Exception Handling Code then JVM Terminates
main() Abnormally and Removes Corresponding Entry from the Stack.
4 https://www.youtube.com/durgasoftware
OCJA
Then JVM Handovers the Responsibility of Exception Handling to the Default
Exception Handler, which is the Part of the JVM.
Default Exception Handler Just Terminates the Program Abnormally and Prints
Exception Information to the Console in the following Format.
Examples:
class Test {
public static void main(String[] args) {
doStuff();
}
public static void doStuff() { doMoreStuff()
doMoreStuff(); ;
doStuff();
}
public static void doMoreStuff() { main()
System.out.println(10/0); Runtime Stack
}
}
RE: Exception in thread "main" java.lang.ArithmeticException: / by zero
at Test.doMoreStuff(Test.java:9)
at Test.doStuff(Test.java:6)
at Test.main(Test.java:3)
class Test {
public static void main(String[] args) {
doStuff();
}
public static void doStuff() {
doMoreStuff();
System.out.println(10/0);
}
public static void doMoreStuff() {
System.out.println("Hello");
}
}
Hello
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Test.doStuff(Test.java:7)
at Test.main(Test.java:3)
5 https://www.youtube.com/durgasoftware
OCJA
class Test {
public static void main(String[] args) {
doStuff();
System.out.println(10/0);
} Hello
public static void doStuff() { Hi
doMoreStuff(); Exception in thread "main"
System.out.println("Hi"); java.lang.ArithmeticException: / by zero
} at Test.main(Test.java:4)
public static void doMoreStuff() {
System.out.println("Hello");
}
}
Note:
In Our Program if all Methods Terminated Normally, then Only the Program will be
Terminated Normally.
In Our Program if at least One Method terminates Abnormally then the Program
Termination is Abnormal Termination.
Exception Hierarchy
Exception: Most of the Cases Exceptions are Caused by Our Program and these are Re-
Coverable.
Eg:
If Our Programming Requirement is to Read Data from the File locating at London.
At Runtime if London File is Not Available then we get FileNotFoundException.
If FileNotFoundException Occurs we can Provide Local File to Continue Rest of the
Program Normally.
Programmer is Responsible to Recover Exception.
Error:
Most of the Cases Errors are Not Caused by Our Program and these are Due to Lack
of System Resources.
Errors are Non- Recoverable.
Eg:
If OutOfMemoryError Occurs, being a Programmer we can't do anything and the
Program will be terminated Abnormally.
System Admin OR Server Admin is Responsible to Increase Heep Memory.
6 https://www.youtube.com/durgasoftware
OCJA
Checked Vs Unchecked Exception:
Checked Exceptions:
The Exceptions which are Checked by the Compiler for Smooth Execution of the
Program at Runtime are Called Checked Exceptions.
Compiler Checks whether we are handling Checked Exceptions OR Not. If we are
Not handling then we will get Compile Time Error.
Eg:
HallTicketMissingException, PenNotWorkingException, FileNotFoundException, Etc.
Unchecked Exceptions:
The Exceptions which are Not Checked by the Compiler are Called Unchecked
Exception.
Compiler won't Check whether we are Handle OR Not Unchecked Exceptions.
Eg: ArithmeticException, NullPointerException, BombBlostException, Etc.
Note:
Whether the Exception is Checked OR Unchecked Compulsory it will Occur at
Runtime Only.
There is No Chance of occurring any Exception at Compile Time.
Runtime Exceptions and its Child Classes, Errors and its Child Classes are
Unchecked Exceptions Excetp these all remaining are Considered as Checked
Exceptions.
7 https://www.youtube.com/durgasoftware
OCJA
Fully Checked Vs Partially Checked:
A Checked Exception is Said to be Fully Checked if and Only if all its Child Classes also
Checked.
Eg: IOException, InterruptedException, ServletException, Etc...
A Checked Exception is Said to be Partially Checked if and Only if Some of its Child
Classes are Unchecked.
Eg: Throwable, Exception.
2) RuntimeException Unchecked
4) Error Unchecked
6) ArithmeticException Unchecked
7) NullPointerException Unchecked
try
{
//Risky Code
}
catch (Exception e)
{
//Handling Code
}
8 https://www.youtube.com/durgasoftware
OCJA
Without try – catch With try - catch
class Test { class Test {
public static void main(String[] args) { public static void main(String[] args) {
System.out.println("Statement 1"); System.out.println("Statement 1");
System.out.println(10/0); try {
System.out.println("Statement 2"); System.out.println(10/0);
} }
} catch(ArithmeticException e) {
System.out.println(10/2);
Statement 1 }
RE: Exception in thread "main" System.out.println("Statement 2");
java.lang.ArithmeticException: / by zero }
at Test.main(Test.java:4) } Statement 1
5
Abnormal Termination Normal Termination Statement 2
try {
Statement 1;
Statement 2;
Statement 3;
}
catch(X e) {
Statement 4;
}
Statement 5;
Conclusions:
Within the try Block if any where an Exception raised then Rest of the try Block
won't be executed even though we handled that Exception.
Hence within the try Block we have to Take Only Risky Code and Hence Length of
the try Block should be as Less as Possible.
If there is any Statement which raises an Exception and it is Not Part of the try
Block then it is Always Abnormal Termination.
In Addition to try Block there May be a Chance of raising an Exception Inside catch
and finally Blocks Also.
9 https://www.youtube.com/durgasoftware
OCJA
Methods to Print Exception Information
class Test {
public static void main(String[] args) {
try {
System.out.println(10/ 0);
}
catch (ArithmeticException e) {
e.printStackTrace(); //RE: java.lang.ArithmeticException: / by zero
at Test.main(Test.java:4)
System.out.println(e); //RE: java.lang.ArithmeticException: / by zero
System.out.println(e.getMessage()); /// by zero
}
}
}
10 https://www.youtube.com/durgasoftware
OCJA
try with Multiple catch Blocks
The way of handling an Exception is varied from Exception to Exception. Hence for
Every Exception Type we have to define a Separate catch Block. Hence try with
Multiple catch Blocks is Possible and Recommended to Use.
try { try {
:::::::::::: ::::::::::::::
:::::::::::: ::::::::::::::
} }
catch (Exception e) { catch (ArithmeticException e) {
::::::::::: //Perform these an Alternative
::::::::::: ArithmeticException
} }
catch (NullPointerException e) {
Not Recommended //Handling Related to null
}
catch (FileNotFoundException) {
//Use Local File Instead of Remote File
}
catch (SQLException e) {
//Use MySQL DB Instead of Oracle
}
catch (Exception e) {
Default Exception Handling
}
Recommended
Note:
If try with Multiple catch Blocks Present then the Order of catch Blocks are Very
Important. It should be from Child to Parent.
By Mistake if we are trying to Take Parent to Child then we will get Compile Time
Error Saying: exception XXX has already been caught
try {}
catch (Exception e) {}
catch (ArithmeticException e) {} //CE: exception ArithmeticException has already been caught
try {}
catch (ArithmeticException e) {}
catch (Exception e) {}
For any Exception if we are writing 2 Same catch Blocks we will get Compile Time
Error.
11 https://www.youtube.com/durgasoftware
OCJA
try {}
catch(ArithmeticException e) {}
catch(ArithmeticException e) {} //CE: error: exception ArithmeticException has already been caught
finally Block
It is Never Recommended to Define Clean-up Code Inside try Block. Because there
is No Guaranty for the Execution of Every Statement Inside try Block.
It is Never Recommended to Define Clean-up Code Inside catch Block. Because if
there is No Exception then catch Block won't be executed.
Hence we required Some Place to Maintain Clean-up Code which should be
executed Always irrespective of whether Exception raised OR Not raised and
whether Handled OR Not Handled. Such Type of Best Place is Nothing but finally
Block.
Hence the Main Objective of finally Block is to Maintain Clean-up Code.
try {
//Risky Code
}
catch(X e) {
//Handling Code
}
finally {
//Clean Up Code
}
12 https://www.youtube.com/durgasoftware
OCJA
class Test {
public static void main(String[] args) {
try {
System.out.println ("try");
System.out.println (10/0); try
} finally
catch (NullPointerException e) { Exception in thread "main"
System.out.println ("catch"); java.lang.ArithmeticException: / by zero
} at Test.main(Test.java:5)
finally {
System.out.println ("finally");
}
}
}
finally Vs return:
If return Statement Present Inside try OR catch Blocks 1st finally will be executed and
after that Only return Statement will be Considered i.e. finally Block Dominates return
Statement.
class Test {
public static void main(String[] args) {
try {
System.out.println("try");
return;
}
catch(Exception e) {
System.out.println("catch");
}
finally {
System.out.println("finally");
}
} try
} finally
If try-catch-finally Blocks having return Statements then finally Block return Statement
will be Considered i.e. finally Block return Statement has More Priority than try and
catch Block return Statements.
13 https://www.youtube.com/durgasoftware
OCJA
class Test {
public static void main(String[] args) {
System.out.println(m1()); //999
}
public static int m1() {
try {
return 777;
}
catch(Exception e) {
return 888;
}
finally {
return 999;
}
}
}
finally Vs System.exit(0):
There is Only One Situation where the finally Block won't be executed that is
whenever we are System.exit(0).
Whenever we are using System.exit(0) then JVM itself will be Shutdown and hence
finally Block won't be executed. That is System.exit(0) Dominates finally Block.
class Test {
public static void main(String[] args) {
try {
System.out.println("try");
System.exit(0);
}
catch(Exception e) {
System.out.println("catch");
}
finally {
System.out.println("finally");
}
}
} try
System.exit(0);
☀ We can Use this Method to Exit (Shut Down) the System (JVM) Programmatically.
☀ The Argument Represents as Status Code.
☀ Instead of 0 we can Pass any Valid int Value.
☀ 0 Means Normal Termination, Non- Zero Means Abnormal Termination.
☀ So this status code internally used by JVM.
14 https://www.youtube.com/durgasoftware
OCJA
☀ Whether it is 0 OR Non- Zero Effect is Same in Our Program but this Number
Internally used by JVM.
final:
final is a Modifier is Applicable for Classes, Methods and Variables.
If a Class declared as final then we can't Create Child Class. That is Inheritance is
Not Possible for final Classes.
If a Method declared as final then we can't Override that Method in Child Classes.
If a Variable declared as final then we can't Perform Re- Assignment for that
Variable.
finally:
finally is a Block Always associated with try-catch to Maintain Clean Up Code.
The Specialty of finally Block is it will be executed Always Irrespective of whether
Exception raised OR Not and whether Handled OR Not Handled.
finalize():
finalize() is a Method Always Called by the Garbage Collector Just before Destroying
an Object to Perform Clean Up Activities.
Once finalize() Completes Automatically Garbage Collector Destroys that Object.
Note:
finally() is Responsible to Perform Object Level Clean-Up Activities whereas finally
Block is Responsible to Perform try Block Level Clean-Up Activities i.e. whatever
Resources we Opened at the Time of try Block will be Closed Inside finally Block
It is Highly Recommended to Use finally Block than finalize()because we can't
Expect Exact Behavior of Garbage Collector. It is JVM Vendor Dependent.
15 https://www.youtube.com/durgasoftware
OCJA
Case 2: If an Exception raised at Statement 2 and Corresponding catch Block Matched.
then 1, 4, 5, 6 Normal Termination.
16 https://www.youtube.com/durgasoftware
OCJA
Case 3: If an Exception raised at Statement 2 and Corresponding catch Block is Not
Matched 1 and 11 Abnormal Termination.
Case 4: If an Exception raised at Statement 5 and Corresponding Inner catch Block has
Matched 1, 2, 3, 4, 7, 8, 9, 11, 12 Normal Termination.
Case 5: If an Exception raised at Statement 5 and Inner catch Block has Not Matched
but Outer catch Block has Matched. 1, 2, 3, 4, 8, 10, 11, and 12 Normal Termination.
Case 6: If an Exception raised at Statement 5 and Both Inner and Outer catch Blocks
are Not Matched then 1, 2, 3, 4, 8, and 11 Abnormal Termination.
Case 10: If an Exception raised at Statement 8 and Corresponding catch Block Not
Matched 1, 2, 3,.,.,.,., 11 Abnormal Termination.
Case 11: If an Exception raised at Statement 9 and Corresponding catch Block Matched
1, 2, 3,.,.,.,., 8, 10, 11, and 12 Normal Termination.
Case 12: If an Exception raised at Statement 9 and Corresponding catch Block Not
Matched 1, 2, 3,.,.,.,.,8, and 11 Abnormal Termination.
Note:
We can Take try – catch – finally Inside try Block i.e. Nesting of try – catch – finally
is Always Possible.
More Specific Exceptions can be handled by Inner catch Block and Generalized
Exceptions are handled by Outer catch Blocks.
Once we entered into the try Block without executing finally Block the Control
Never Comes Up.
If we are Not entering into the try Block then finally Block won’t be executed.
17 https://www.youtube.com/durgasoftware
OCJA
class Test {
public static void main(String[] args) {
try {
System.out.println(10/0);
}
catch(ArithmeticException e) { 1) CE
System.out.println(10/0); 2) RE: ArihmeticException
} 3) RE: NullPointerException
finally { 4) RE: ArihmeticException and RE: NullPointerException
String s = null;
System.out.println(s.length());
}
}
}
Note: Default Exception Handler can Handle Only One Exception at a Time i.e. the
Most Recently raised Exception.
try {}
catch (X e) {}
try {}
catch (X e) {}
catch (Y e) {}
try {}
catch (X e) {}
catch (X e) {} // CE: exception ArithmeticException has already been caught
try {}
finally {}
try {}
catch (X e) {}
System.out.println("Hello");
catch (Y e) {} //CE: 'catch' without 'try'
try {}
catch (X e) {}
System.out.println("Hello");
finally {} //CE: 'finally' without 'try'
try {}
finally {}
catch (X e) {} //CE: 'catch' without 'try'
try {}
catch (X e) {}
try {}
finally {}
try {}
catch (X e) {}
finally {}
finally {} //CE: 'finally' without 'try'
try {}
catch (X e) {
try {}
catch (Y e1) {}
}
try {}
catch (X e) {}
finally {
try {}
catch (Y e1) {}
finally {}
}
try {
try {} //CE: 'try' without 'catch', 'finally' or resource declarations
}
catch (X e) {}
19 https://www.youtube.com/durgasoftware
OCJA
try //CE: '{' expected
System.out.println("Hello");
catch (X e1) {} //CE: 'catch' without 'try'
try {}
catch (X e) //CE:'{' expected
System.out.println("Hello");
try {}
catch (NullPointerException e1) {}
finally //CE: '{' expected
System.out.println("Hello");
throw Keyword:
Sometimes we can Create Exception Object Explicitly and we can Handover Our
Created Exception Object to the JVM Manually. For this we have to Use throw key
Word.
Eg:
throw new ArithmeticException("/by zero");
In General we can Use throw Key Word for Customized Exceptions but Not for
pre-defined Exceptions.
class Test {
public static void main(String[] args) {
System.out.println(10/0);
Case – 1 }
}
class Test1 {
public static void main(String[] args) {
throw new ArithmeticException("/ by zero Explicitly");
}
}
Case – 2
//Exception in thread "main" java.lang.ArithmeticException: / by zero Explicitly
20 https://www.youtube.com/durgasoftware
OCJA
In the Case – 1 main() is Responsible to Create Exception Object and Handover to the JVM.
This Total Activity will be performed Internally.
In the Case – 2 Programmer creating Exception Object Explicitly and Handover to the JVM
Manually.
Hence the Main Purpose of throw Key Word is to Handover Our Created Exception Object
to the JVM Manually.
Case 1: throw e;
If ‘e’ Refers ‘null’ then we will get NullPointerException.
class Test {
static ArithmeticException e = new ArithmeticException();
public static void main(String[] args) {
throw e;
}
}
class Test {
static ArithmeticException e;
public static void main(String[] args) {
throw e;
}
}
Case 2: After throw Statement we are Not allowed to write any Statements Directly
Otherwise we will get Compile Time Error Saying unreachable statement.
class Test {
public static void main(String[] args) {
System.out.println(10/0);
System.out.println("Hello");
}
}
class Test {
public static void main(String[] args) {
throw new ArithmeticException("/by zero");
System.out.println("Hello"); //CE: unreachable statement
}
}
21 https://www.youtube.com/durgasoftware
OCJA
Case 3: We can Use throw Key Word Only for Throwable Types. Otherwise we will get
Compile Time Error Saying incompatible types.
In Our Program if there is any Chance of raising Checked Exception then Compulsory
we should Handled that Checked Exception Otherwise we will get Compile Time Error
Saying unreported exception XXX; must be caught or declared to be thrown.
1) By Using try-catch
2) By Using throws Key Word
class Test {
public static void main(String args[]) {
try {
Thread.sleep(5000);
}
catch (InterruptedException e) {}
}
}
22 https://www.youtube.com/durgasoftware
OCJA
2nd Way: By Using throws Key Word
We can use throws Key Word to Delegate the Responsibility of Exception Handling
to the Caller Method (It May be Another Method OR JVM). Then Caller is
Responsible to Handle that Checked Exception.
throws Key Word required Only for Checked Exceptions.
Usage of throws Key Word for Unchecked Exceptions there is No Use.
throws Key Word required Only to Convince Compiler and it doesn’t Prevent
Abnormal Termination of the Program.
Hence Recommended to Use try- catch- finally Over throws Key Word.
class Test {
public static void main(String[] args)throws InterruptedException {
Thread.sleep(5000);
}
}
Conclusions:
1) We can Use to Delegate the Responsibility of Exception
Handling to the Caller.
class Test {
public static void main(String[] args)throws InterruptedException {
doStuff();
}
public static void doStuff()throws InterruptedException {
doMoreStuff();
}
public static void doMoreStuff()throws InterruptedException {
Thread.sleep(5000);
}
}
In the Above Program if we Remove at-least One throws Statement then the Code
won't Compile. We will get CE: unreported exception InterruptedException; must be
caught or declared to be thrown
Case 1: We can Use throws Key Word Only for Methods and Constructors but Not for
Classes.
23 https://www.youtube.com/durgasoftware
OCJA
class Test throws Exception {
Test() throws Exception {} √
public static void m1() throws Exception {} √
}
Case 2:
We can Use throws Key Word Only for Throwable Types but Not for Normal Java
Classes. Otherwise we will get Compile Time Error Saying
incompatible types
required: java.lang.Throwable class Test {
found: Test public static void main(String[] args) throws Test {}
}
Case 4:
Inside try Block, if there is No Chance of raising an Exception then we can't write catch
Block for that Exception. Otherwise we will get Compile Time Error Saying CE:
exception XXX is never thrown in body of corresponding try statement. But this Rule
is Applicable Only for Fully Checked Exceptions.
class Test { class Test {
public static void main(String[] args) { public static void main(String[] args) {
try { try {
System.out.println("Hello"); System.out.println("Hello");
} }
catch (ArithmeticException e) {} catch (Exception e) {}
} }
} Unchecked Exception } Partially Checked Exception
class Test {
public static void main(String[] args) {
try {
System.out.println("Hello");
}
catch (Error e) {}
}
} Unchecked Exception
Output: Hello
4) unreachable statement
5) incompatible types
required: java.lang.Throwable
found: Test
25 https://www.youtube.com/durgasoftware
OCJA
6) try without catch or finally
java CustExceptionDemo 70
Exception in thread "main" TooYoungException: Please Wait Some More Time U will get Best
Match
at CustExceptionDemo.main(CustExceptionDemo.java:15)
java CustExceptionDemo 50
U will get Match Details Soon by Email...!
java CustExceptionDemo 15
Exception in thread "main" TooOldException: Your Age Already Crossed Marriage Age No Chance
of getting Match
26at CustExceptionDemo.main(CustExceptionDemo.java:18)
https://www.youtube.com/durgasoftware
OCJA
Note:
☀ throw Key Word is Best Suitable for Customized Exceptions but Not for Pre-defined
Exceptions.
☀ It is Highly Recommended to define Customized Exceptions as Unchecked i.e. we
have to extends RuntimeException but Not Exception.
☀ To Make Description Available to Parent Class, from which Default Exception
Handler get these Description.
Top 10 Exceptions
Based on the Person who is raising Exception, all Exceptions are divided into 2 Types.
1) JVM Exceptions
2) Programmatic Exceptions.
JVM Exceptions: The Exceptions which are raised Automatically by the JVM whenever
a Particular Event Occurs Such Type of Exceptions are Called JVM Exceptions.
Eg: ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException Etc.
Programmatic Exceptions:
The Exceptions which are raised Explicitly either by Programmer OR by API Developer
are Called Programmatic Exceptions.
Eg: IllegalArgumentException, TooYoungException, Etc.
ArrayIndexOutOfBoundsException:
It is the Child Class of RuntimeException and Hence it is Unchecked.
Raised Automatically by the JVM Whenever we are trying to Access Array Element
with Out of Range Index.
Eg:
int[] a = new int[10];
System.out.println(a[0]); //0
System.out.println(a[100]); //RE: java.lang.ArrayIndexOutOfBoundsException: 100
System.out.println(a[-100]); //RE: java.lang.ArrayIndexOutOfBoundsException: -100
NullPointerException:
It is the Child Class of RuntimeException and Hence it is Unchecked.
Raised Automatically by the JVM whenever we are trying to Perform any Method
Call on null Reference.
StackOverFlowError:
It is the Child Class of Error and Hence it is Unchecked.
Raised Automatically by the JVM whenever we are trying to Perform Recursive Method
Call.
27 https://www.youtube.com/durgasoftware
OCJA
class Test {
public static void m1() {
m2(); Recursive Method Call
::
}
::
public static void m2() {
::
m1();
::
m2()
}
::
m1()
public static void main(String[] args) {
::
main(
m1(); //RE: java.lang.StackOverflowError
} ) :: Stack
Runtime
::
}
::
::
ClassCastException: ::
It is the Child Class of RuntimeException and Hence :: it is Unchecked.
Raised Automatically by the JVM whenever we are trying to Type Cast Parent
Object to Child Type.
Eg:
String s = new String("abc");
Object o = (Object)s; //√
NoClassDefFoundError:
It is the Child Class of Error and Hence it is Unchecked.
Raised Automatically by the JVM whenever JVM Unable to find required .class File.
Eg: java Test
If Test.class is Not Available then we will get RuntimeException Saying
java.lang.NoClassDefFoundError: Test
ExceptionInInitializerError:
It is the Child Class of Error and Hence it is Unchecked.
Raised Automatically by the JVM if any Exception Occurs while executing Static
Variable Assignments and Static Blocks.
class Test {
static int i = 10/0; RE: Exception in thread "main" java.lang.ExceptionInInitializerError
} Caused by: java.lang.ArithmeticException: / by zero
28 https://www.youtube.com/durgasoftware
OCJA
class Test {
static {
Exception in thread "main"
String s = null;
java.lang.ExceptionInInitializerError
System.out.println(s.length());
Caused by: java.lang.NullPointerException
}
}
IllegalArgumentException:
It is the Child Class of RuntimeException and Hence it is Unchecked.
Raised Explecitly by the Programmer OR by API Developer to Indicate that a Method
has been invoked with Illegal Argument.
class Test {
public static void main(String[] args) {
Thread t = new Thread();
t.setPriority(10); √
t.setPriority(100); RE: Exception in thread "main" java.lang.IllegalArgumentException
} at java.lang.Thread.setPriority(Thread.java:1125)
} at Test.main(Test.java:5)
The Valid Range of Thread Priorities is 1 to 10. If we are trying to Set the Priourity
with any Other Value we will get Runtime Exception Saying
IllegalArgumentException.
NumberFormatException:
It is the Direct Child Class of IllegalArgumentException, which is Child Class of
RuntimeException and Hence it is Unchecked.
Raised Explecitly either by Programme OR by API Developer to Indicate that we are
trying to Convert String to Number but the String is Not Properly Formatted.
IllegalStateException:
It is the Child Class of RuntimeException and Hence it is Unchecked.
Raised Explecitly either by Programmer OR by API Developer to Indicate that a
Method has been invoked at Wrong Time.
Examples:
1) After Starting a Thread we are Not allowed to Re- Start the Same Thread Once
Again. Otherwise we will get Runtime Exception Saying IllegalThreadStateException.
Thread t = new Thread();
t.start();
t.start(); //RE: java.lang.IllegalThreadStateException
2) Once Session Expires we are Not allow to Call any Method on that Session Object. If
we are trying to Call we will get Runtime Exception Saying IllegalStateException.
29 https://www.youtube.com/durgasoftware
OCJA
HttpSession session = req.getSession();
System.out.println(session.getId()); //Valid
session.invalidateI();
System.out.println(session.getId()); //RE: IllegalStateException
AssertionError:
It is the Child Class of Error and Hence it is Unchecked.
Raised Explecitly to Indicate that assert Statement Fails.
Eg: assert(x > 10);
if(x !> 10) then we will get Runtime Exception Saying AssertionError.
1) ArrayIndexOutOfBoundsException
2) NullPointerException
3) StackOverflowError
Raised by JVM and Hence
4) ClassCastException these are JVM Exceptions
5) NoClassDefFoundError
6) ExceptionInInitializerError
7) IllegalArgumentException
Raised by Explicitly either by
8) NumberFormatException Programmer OR by API
Developer and Hence they are
9) IllegalStateException Programmatic Exceptions
10) AssertionError
30 https://www.youtube.com/durgasoftware
OCJA
1.7 Version Enhancements
In 1.7 Version as the Part of Exception Handling the following 2 Concepts Introduced.
try with Resources
Multi catch Block
try with Resources: Until 1.6 Version it is Highly Recommended to write finally Block
to Close All Resources which are Opened as the Part of try Block.
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("Input.txt");
//Use br based on Our Requirement
}
catch (InterruptedException e) {
//Handling Code
}
finally {
if (br != null) {
br.close();
}
}
To Overcome these Problems SUN People Introduce try with Resources in 1.7 Version.
try (BufferedReader br = new FileReader("Input.txt")) { Resource
//Use br based on Our Requirements. br will be Closed Automatically Once the Control
Reaches End of try either Normally OR Abnormally
}
catch (InterruptedException e) {}
The Main Advantage of try with Resources is the Resources which are Opened as
the Part of try Block will be Closed Automatically and we are Not required to Close
Explicitly. It Reduces Complexity of the Programming.
It is Not required to write finally Block Explicitly and Hence Length of the Code will
be Reduced and Readability will be Improved.
31 https://www.youtube.com/durgasoftware
OCJA
Conclusions:
We can Declare Multiple Reasons and All these Resources should be Separated with
‘;’.
Syntax: try (R1; R2; R3) {
------------------
}
Eg: try ( FileWriter fw = new FileWriter("Output.txt");
FileWriter fw = new FileWriter("Input.txt"); ) {
--------------
}
This Interface introduced in 1.7 Version and it contains Only One Method
public void close();
import java.io.*;
class TryWithResources {
public static void main (String args[]) throws Exception {
try (BufferedReader br = new BufferedReader (new FileReader ("abc.txt"))) {
br = new BufferedReader (new FileReader ("Input.txt"));
}
} //CE: auto-closeable resource br may not be assigned
}
Until 1.6 Version try should be followed by either catch OR finally but from 1.7
onwards we can Take Only try with Resources without catch and finally Blocks.
Eg: try (R) {-----------}
The Main Advantage of try with Resources is finally Block will become Dummy
because we are required to Close the Resources Explicitly.
32 https://www.youtube.com/durgasoftware
OCJA
Multi Catch Block (Catch Block with Multiple Exceptions)
Until 1.6 Version even though Multiple Exceptions having Same Handling Code
Compulsory we have to write a Separate catch Block for Every Exception.
try {
-------
}
catch (ArithmeticException e) {
e.printStackTrace();
}
catch (NullPointerException e) {
e.printStackTrace();
}
catch (ClassCastException e) {
System.out.println(e.getMessage());
}
catch (IOException e) {
System.out.println(e.getMessage());
}
The Problem in this Approach is it Increases Length of the Code and Reduces
Readability.
To Overcome this Problem SUN People Introduced Multi Catch Block in 1.7 Version.
In this Approach we can write a Single Catch Block which can Handle Multiple
Exceptions of different Types.
try {
-------
}
catch (ArithmeticException | NullPointerException e) {
e.printStackTrace();
}
catch (ClassCastException | IOException e) {
System.out.println(e.getMessage());
}
class MultiCatchBlock {
public static void main(String[] args) {
try {
//System.out.println(10/ 0);
String s = null;
System.out.println(s.length());
}
catch (ArithmeticException | NullPointerException e) {
System.out.println(e); //java.lang.NullPointerException
}
}
}
33 https://www.youtube.com/durgasoftware
OCJA
If Mutli Catch Block there should Not be any Relation between Exception Types
(Like Parent to Child OR Child to Parent OR Same Type) Otherwise we will get
Compile Time Error.
Exception Propagation:
☀ Within a Method if an Exception raised and if we are Not Handle that Exception
then that Exception Object will be propagated to Automatically to the Caller
Method.
☀ Then Caller Method is Responsible to Handle that Exception.
☀ This Process is Called Exception Propagation.
Exception Propagation
m1() { m2() {
m2() Exception
} }
Re-Throwing Exception
We can Use this Approach to Convert One Exception Type to Another Exception Type.
try {
System.out.println(10/ 0);
}
catch (ArithmeticException e) {
throw new NullPointerException();
}
34 https://www.youtube.com/durgasoftware
OCJA
Q1. Given the code fragment:
1) class X
2) {
3) public void printFileContent()
4) {
5) //Line-1
6) throw new IOException();//Line-2
7) }
8) }
9) public class Test
10) {
11) public static void main(String[] args)//Line-3
12) {
13) X x= new X();
14) x.printFileContent();//Line-4
15) //Line-5
16) }
17) }
A. Replace Line-3 with public static void main(String[] args) throws Exception
B. Replace Line-4 with:
1) try
2) {
3) x.printFileContent();
4) }
5) catch (Exception e){}
6) catch (IOException e){}
C. Replace Line-3 with public static void main(String[] args) throws IOException
D. Replace Line-2 with throw IOException("Exception Raised");
E. At Line-5 insert throw new IOException();
Answer: A, C
35 https://www.youtube.com/durgasoftware
OCJA
9) System.out.println("Checking Card");
10) }
11) public static void main(String[] args)
12) {
13) Test t = new Test();
14) int cardNo=1234;
15) t.checkCard(cardNo);//Line-2
16) t.readCard(cardNo);//Line-3
17) }
18) }
A. Checking Card
Reading Card
Answer: D
Q3. Given the following code for the classes MyException and Test:
36 https://www.youtube.com/durgasoftware
OCJA
24) catch (RuntimeException e)
25) {
26) System.out.println("B");
27) }
28) }
29) }
Answer: E
A. element 0
element 1
B. null element 0
null element 1
C. null
null
D. A NullPointerException is thrown at runtime
Answer: D
37 https://www.youtube.com/durgasoftware
OCJA
Q5. Given the code fragment:
A.
Invalid Name
omas
null
null
B.
Invalid Name
C.
Invalid Name
omas
D.
Compilation Fails
Answer: A
38 https://www.youtube.com/durgasoftware
OCJA
Q6. Given the code fragment:
1) import java.util.*;
2) public class Test
3) {
4) public static void main(String[] args)
5) {
6) ArrayList l = new ArrayList();
7) String[] s;
8) try
9) {
10) while(true)
11) {
12) l.add("MyString");
13) }
14) }
15) catch (RuntimeException e)
16) {
17) System.out.println("Caught a RuntimeException");
18) }
19) catch (Exception e)
20) {
21) System.out.println("Caught an Exception");
22) }
23) System.out.println("Ready to use");
24) }
25) }
Answer: C
A. Improves the program structure because the error handing code is separated from the normal
program function.
C. Improves the program structure beacuase the programmer can choose where to handle
exceptions
39 https://www.youtube.com/durgasoftware
OCJA
D. Imporves the program structure because exceptions must be handled in the method in which
they occurred.
E. Allows the creation of new exceptions that are tailored to the particular program being created.
Answer:A,C,E
Answer: B,C,E
Ans: B,E
40 https://www.youtube.com/durgasoftware
OCJA
FAQ’s
1) What is An Exception?
8) If try With Multiple catch Block Present, Is Order of catch Blocks Important in
Which Order We Have To Take?
10) If An Exception Raised Inside catch Block Then What Will Happen?
17) If Return Statement Present Inside try, is Finally Block Will Be Executed?
18) What is The Difference Between final, finally And finalize ()?
41 https://www.youtube.com/durgasoftware
OCJA
25) After throw is it Allow To Take Any Statement Directly?
30) If We Are Taking catch Block For An Exception But There is No Chance of Rising
That Exception in try Then What Will Happen?
32) Which Class Act As Root For Entire Java Exception Hierarchy?
35) What is Difference Between Partially Checked And Fully Checked Exception?
39) Can You Give The Most Common Occurred Exception in Your Previous Project?
40) Explain The Cases Where You Used Exception Handling in Your Previous
Project?
42 https://www.youtube.com/durgasoftware