0% found this document useful (0 votes)
18 views32 pages

Exception Handling

The document provides a comprehensive overview of exception handling in Java, covering topics such as runtime stack mechanics, default exception handling, control flow in try-catch blocks, and the differences between various exception types. It emphasizes the importance of handling exceptions gracefully to ensure normal program termination and includes examples of how to implement exception handling using try-catch blocks. Additionally, it discusses the significance of keywords like 'final', 'finally', and 'finalize', as well as the concept of customized exceptions.

Uploaded by

stunning sathvik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views32 pages

Exception Handling

The document provides a comprehensive overview of exception handling in Java, covering topics such as runtime stack mechanics, default exception handling, control flow in try-catch blocks, and the differences between various exception types. It emphasizes the importance of handling exceptions gracefully to ensure normal program termination and includes examples of how to implement exception handling using try-catch blocks. Additionally, it discusses the significance of keywords like 'final', 'finally', and 'finalize', as well as the concept of customized exceptions.

Uploaded by

stunning sathvik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Exception Handling:

1> Introduction
2> Run time stack mechanics
3> Default exception handlining in java
4> Control flow in try catch
5> Control flow in try catch
6> Methods to print exception information
7> Try with multiple catch block
8> Finally block
9> Difference between final, finally finalize
10> Control flow in try catch finally
11> Control flow in nested try-catch-finally
12> Various possible combination of try catch finally
13> Throw keywords.
14> Throws keywords.
15> Exception handling keywords summery
16> Varius possible compile time error in exception
17> Customized or used defined exception
18> Top 10 exception
19> 1.7 version enhancement
➢ Try with resource
➢ Multi catch blocks

Exception:

An unexpected unwanted event that disturbs normal flow of program is called


exception.

Example:

TyreePancherd exception

> >>>>>>_____ real world exception

Sleeping exception

It is highly recommended to handle exception and the main objective is


gracefully termination of the program.

Exception handling does not mean repairing an exception we have to provide


alternative way to continue rest of the program normally is the concept of
exception handling.

1|Page
Example:

Our program requirement is to read data from remote file locating at London at
runtime if London file is not available our program should not be terminate
abnormally we provide some local file to control rest of the program normally
this way of defining alternative is nothing but exception handling.

**difference between exception and exception handling

Try{

Read data from remote file risky code

Located at London

Catch (fileNotFoundException e) {

Use local file and continue

Rest of the program execution

Runtime Stack Mechanism:

1> for every thread ,JVM will crate a runtime stack each and every method
call performed by that thread will be stored in the corresponding stack.
2> Each entry in the stack frame or activation record.
3> After completing every method call the corresponding entry from the
stack will be removed.
4> After completing all method calls the stack will be destroyed by JVM
just before terminating the thread.
public class demo {
public static void main(String[] args) {
dostuff();
}

private static void dostuff() {


doMorestuf();
}

private static void doMorestuf() {


System.out.println("hello");

}
Output:
hello

2|Page
Default exception handling:

Inside a method , if any exception occurs, the method in which it is raised is


raised is responsible to create exception object by including the following
information

➢ Name of exception
➢ Description of exception
➢ Location at which exception occurs(stack trace)

After creating exception object method handovers that object to the JVM.
JVM will check whether the method contains any exception handling code or
not.

If the caller method handling code ,then JVM terminates that caller method
also abnormally and removes corresponding entry from stack.

This process will be continued until main method and if the main method also
does not contain handling code, then JVM terminates main method also
abnormally and removes corresponding entry from the Stack.

The JVM handovers responsibility of exception handling to default exception


handler which is a part of the JVM.

Default exception handler prints exception information inn the following format
and terminates program abnormally.

Exception in thread xxxxx

Name of the Exception : Description

Stack Trace

3|Page
public class demo {
public static void main(String[] args) {
dostuff();
}

private static void dostuff() {


doMorestuf();
}

private static void doMorestuf() {


System.out.println(10/0);

}
Exception in thread "main" java.lang.ArithmeticException: / by zero
at excelr/revision.demo.doMorestuf(demo.java:13)
at excelr/revision.demo.dostuff(demo.java:9)
at excelr/revision.demo.main(demo.java:5)

package revision;

public class demo {


public static void main(String[] args) {
dostuff();
System.out.println(10/0);
}

private static void dostuff() {


doMorestuf();
System.out.println("Hi");
}

private static void doMorestuf() {


System.out.println("Hello");

}
Output:
Hello
Hi
Exception in thread "main" java.lang.ArithmeticException: / by zero
at excelr/revision.demo.main(demo.java:6)

public class demo {

4|Page
public static void main(String[] args) {
dostuff();
}

private static void dostuff() {


doMorestuf();
System.out.println(10/0);
}

private static void doMorestuf() {


System.out.println("Hello");

}
Output:
Hello
Exception in thread "main" java.lang.ArithmeticException: / by zero
at excelr/revision.demo.dostuff(demo.java:10)
at excelr/revision.demo.main(demo.java:5)

Note:

In a program, at least one method terminates abnormally then the program


termination is abnormal termination. If all methods terminate normally then only
program termination is normal termination.

Exception Hierarchy:

1. Throwable:- throwable acts as root for java hierarchy

Exception:-

most of the times exception are caused by our program and this is
recoverable.

Example:

1. If our programming requirement is to read data from remote file location


London at runtime, if remote file is not available then we will get
RuntimeException: FileNotFoundException.
2. If FileNotFoundException occurs we can provide local file and continue
the rest of the program normally.
try {
// read data from remote file
// Located at London
} catch (FileNotFoundException e) {
// use Local File and continue
// rest of the program execution
}

5|Page
Error:-

1. Most of the time error are not occurred by our program and these are
due to lack of system resources.
2. Errors are non-recoverable.

Example:

If OutOfMemoryError occurs being a programmer we can’t do anything


and program will be terminated abnormally.

System admin or server admin is responsible to increase Heap memory

Checked Exception vs Unchecked Exception:-

The exception which are checked by the compiler for smooth execution of the
program at runtime are called checked exception

Example:

➢ HallTicketMissingException
➢ PenNotWorkingException
➢ FileNotFoundException

In our program if there is a chance of raising checked exception then


compulsory, we should handle that checked exception either by using try catch
or by throws keyword otherwise we will get compile time error.

6|Page
The exception which are not checked by the compiler whether programmer is
handling or not such type of exception is called unchecked exception.

Example:

➢ ArithmaticException
➢ BombBlastException

Note: Whether it checked or unchecked every exception occurs at runtime only


there is no chance of occurring exception at compile time.

Runtime exception and its child classes error and its child classes are unchecked
except this remaining are unchecked.

Fully checked vs Partially checked:

A checked is said to be fully checked if and only if all its child classes are also
checked .

Example :- IOException, InterruptedException

A checked exception is said to be partially checked if and only if some of its


child classes are unchecked.

Example:- Throwable & Exception are example of partially checked


exceptions.

Note: the only partially checked exception in java are exception and throwable.

Describe the behaviours of the following exception:

1> IOException→checked(fully)
2> RuntimeException→unchecked
3> InterruptedException →checked(fully)
4> Error→unchecked
5> Throwable →checked (partially)
6> ArithmaticException →unchecked
7> NullPointerException →Unchecked
8> Exception →Checked Partially
9> FileNotFoundException→checked(fully)

Customized Exception Handling by using try catch:-

It is highly recommended to handle exception.

7|Page
The code which may raise an exception that code is called risky code and we
have to define that code in try block and corresponding handling code we have
to define in catch block
try {
//risky code
}
catch(Exception e) {
//handling code
}
Code without try catch:
public class exceptiondemo {

public static void main(String[] args) {


System.out.println("statement 1");
System.out.println(10/0);
System.out.println("statement 3");
}

}
Output:
statement 1
Exception in thread "main" java.lang.ArithmeticException: / by zero
at excelr/Tulalu.exceptiondemo.main(exceptiondemo.java:7)
abnormal termantion

with try catch block.


package Tulalu;

public class exceptiondemo {

public static void main(String[] args) {


System.out.println("statement 1");
try {
System.out.println(10/0);
}
catch(Exception e) {
System.out.println(10/2);

}
System.out.println("statement 3");
}
}
Output:
statement 1
5
statement 3
normal termination

8|Page
Control flow in try catch
try {
statement 1;
statement 2;
statement 3;
}
catch(Exception x) {
statement 4;
}
statement 5;
case1:

if there is no exception in the above program then the output will be statement
1, 2 ,3 & 5 normal termination.

Case2:

If an exception is raised at statement -2 in the above code and corresponding


catch block matched . then the output will be statement 1,4 &5 normal
termination.

Case3:

If an exception is raised at statement-2 and corresponding catch block is not


matched. Then the output in this case will be statement 1 abnormal termination

Case4:

If an exception is raised at statement4 or statement 5 then it is always


abnormal termination.

Note:

Within the try block if any where an exception is raised then rest of the try
block will not be executed even though we handle that exception hence within
the try block we have to take only risky code and length of try block should be
as less as possible.

In addition to try block there may be a chance of raising an exception inside


catch and finally if any statement which is not a part of try block and raises an
exception then it is always abnormal termination.

9|Page
Methods to print Exception Information:-

Throwable class defines the following methods to print exception information.

Methods Printable format


printStackTrace() Name of exception
description
Stack Trace
toString() Name of Exception
Description
get Message() Description only

public class exceptionmethods {


public static void main(String[] args) {
try {
System.out.println(10/0);
}
catch(ArithmeticException e) {
e.printStackTrace();
}
}

}
Output:
java.lang.ArithmeticException: / by zero
at excelr/Tulalu.exceptionmethods.main(exceptionmethods.java:6)

public class exceptionmethods {


public static void main(String[] args) {
try {
System.out.println(10/0);
}
catch(ArithmeticException e) {
System.out.println(e.toString());
}
}

}
Output:
java.lang.ArithmeticException: / by zero

public class exceptionmethods {


public static void main(String[] args) {
try {
System.out.println(10/0);
}
catch(ArithmeticException e) {
System.out.println(e.getMessage());
}
}
}
/by zero

10 | P a g e
Note: internally default exception handler PrintStackTrace to print exception
information to the console.

Try with multiple catch Blocks:

The way of handling an exception varies from exception to exception ,hence for
every exception type it is highly recommended to take separate catch block i.e..
with multiple catch block is always possible & recommend to use

11 | P a g e
If try with multiple catch blocks are present then the order of catch block is
very important , we have to take child first otherwise we will get exception
saying Exception XXX has already been caught
package Tulalu;

public class exceptionmethods {


public static void main(String[] args) {
try {
System.out.println(10/0);
}
catch(Exception e) {

}
catch(ArithmeticException e) {

}
}

}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
ArithmaticException cannot be resolved to a type

at excelr/Tulalu.exceptionmethods.main(exceptionmethods.java:11)

public class exceptionmethods {


public static void main(String[] args) {
try {
System.out.println(10/0);
}
catch(ArithmeticException e) {

}
catch(Exception e) {

}
}

}
correct

we cannot declare two catch blocks for the same exception otherwise we will
get compile time error.
package Tulalu;

public class exceptionmethods {


public static void main(String[] args) {
try {
System.out.println(10/0);
}
catch(ArithmeticException e) {

12 | P a g e
catch(ArithmeticException e) {

}
}

}
Output: as error
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unreachable catch block for ArithmeticException. It is already
handled by the catch block for ArithmeticException

at excelr/Tulalu.exceptionmethods.main(exceptionmethods.java:11)

final:-

➢ Final is modifier applicable for classes, methods and variable


➢ If a class is declared as final then we cannot extend that class i.e.. we
can’t crate child class for that inheritance is not possible for final
classes.
➢ If a method is final we cant override that method in the child class.
➢ If a variable is declared as final then we can’t perform reassignment
for the variable

Finally:-

➢ It is a block always associated with try catch to maintain cleanup code.

try {
//risky code
}
catch(Exception e) {
//handling code
}
finally {
//clean up
}

➢ The specialty of finally block is it will be executed always irrespective


of whether exception is raised or not and whether it is handled or not

Finalize():-

➢ Finalize() is a method always invoked by garbage collector just before


destroying an object to perform cleanup activities.
➢ Once finalize() method completes immediately garbage collector
destroys that object.

13 | P a g e
Note:- finally block is responsible to perform cleanup activities related to try
block i.e., whatever resources we opened at the part of try block will be closed
inside finally block.

Whereas finalize() is responsible to perform cleanup activities related to object


i.e., whatever resources associated with the object will be deallocate before
destroying an object by using finalize().

Various possible combinations of try-catch-finally:


In try catch finally, order is important. Whenever we are writing try
compulsory, we should write either catch or finally otherwise we will get compile
time error. try without catch or finally is invalid.

Whenever we are writing catch block compulsory try block must be required i.e.,
catch without try is invalid.

Whenever we are writing finally block compulsory we should write try-block i.e.,
finally without try is invalid.

Inside try-catch and finally blocks we can declare try catch and finally blocks.
i.e., Nesting of try catch finally is allowed for try catch finally blocks curly
braces are mandatory.

14 | P a g e
17> 18> 19> 20>
Try{ Try{ Try { } Try{ }
Try{} } Catch(x e){ Catch (x e){
Finally {} Catch(x e) Finally{ } }
} { } Finally {
Catch (x e){ Try{ } CE :- finally Try{ }
} Finally { } without Catch(x e){
valid } Catch }
valid Invalid } valid

21> 22> 23> 24> 25>


Try{ } Try{ } Try Try{ Try{
Catch (x e) { Catch(x e){ Sopln(“try”) } }
} } Catch(x e) Catch(x e) Catch(x e)
Finally { Finally{ } Sopln(“catch”) Sopln(“catch”) {
Finally{ } Finally { } Finally { Finally }
} } { Finally
Invalid } Sopln(“finally”)
Invalid CE:- finally invalid invalid
CE:- finally without without try Invalid
try

15 | P a g e
Throw keyword:

Exception object

Programmer java virtual machine

Some time we can create exception object explicitly we can handover to JVM
manually for this we have to use throw keyword

➢ throw new ArithmeticException(“/by zero”);

handover created creation of ArithmeticException

exception object to the JVM object explicitly

hence the main objective of throw keyword is to handover our created


exception object to the JVM manually.
public class exceptionmethods {
public class exceptionmethods { public static void
public static void main(String[] args) {
main(String[] args) { throw new
ArithmeticException("/by zero");
System.out.println(10/0); }
}
}
} Error:
Error: java.lang.ArithmeticException: / by
java.lang.ArithmeticException: / by zero
zero

in this case main() is responsible to in this case programmer created


create exception object and handover exception object explicitly and
to the JVM. handover to the JVM
Hence the result of the two program is exactly same.

16 | P a g e
Best use of throw keyword is for user defined exception or customize
exception:

Example:

Withdraw (double amount){

If (amount > balance)

Throw new insufficientFundException ();

Case 1:

➢ Throw e;
If e refers to null then we will get NullPointerException();
public class exceptionmethods {

static ArithmeticException e=new ArithmeticException ();


public static void main(String[] args) {
throw e;

}
}
ERROR:
Exception in thread "main" java.lang.ArithmeticException
at excelr/Tulalu.exceptionmethods.<clinit>(exceptionmethods.java:5)

public class exceptionmethods {

static ArithmeticException e;
public static void main(String[] args) {
throw e;

}
}
Error:
Exception in thread "main" java.lang.NullPointerException: Cannot throw
exception because "Tulalu.exceptionmethods.e" is null
at excelr/Tulalu.exceptionmethods.main(exceptionmethods.java:7)

case 2:

After throw statement we are not allowed to write any statement directly
otherwise we will get compile time error saying unreachable statement.
public class exceptionmethods {

public static void main(String[] args) {


System.out.println(10/0);
System.out.println("hello");
}
}
Error: java.lang.ArithmeticException: / by zero

17 | P a g e
Case 3

We can use throw keyword only for throwable types if we are trying to use for
normal java object we will get compile time error saying incompatible type.
public class exceptionmethods {

public static void main(String[] args) {


throw new exceptionmethods();
}
}
Error:
Ce:- Unresolved compilation problem

Throws keyword:

In our program if there is a possibility of raising checked exception then


compulsory we should handled that exception other wise we will get compile time
error saying unreported exception must be caught // declared to be thrown.
public class exceptionmethods {

public static void main(String[] args) {


PrintWriter pw =new PrintWriter("abc.txt");
pw.println("hello world");
}
}
Error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type FileNotFoundException

public class exceptionmethods {

public static void main(String[] args) {


Thread.sleep( 100000);
}
}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type InterruptedException

We can handle this compilation error by using the following two ways:

1> By using try catch block


public class exceptionmethods {
public static void main(String[] args) {
try {
Thread.sleep(100000);
}
catch(InterruptedException e) {
}
}

18 | P a g e
2> By using throws keyword

We can use throws keyword to delegate responsibility of exception handling to


the caller it may be another method or JVM.
public class exceptionmethods {

public static void main(String[] args) throws InterruptedException{

Thread.sleep(100000);

}
}

Throws keywords only required for checked exception and uses of throws for
unchecked exception there is no use ,there is no impact

Throws keyword only required to convince compiler and uses of throws keywords
doesn’t prevent abnormal termination of the program.
package Tulalu;

public class demoooo {


public static void main(String[] args)throws InterruptedException {
dostuff();

private static void dostuff()throws InterruptedException {


domoreStuff();
}

private static void domoreStuff()throws InterruptedException {


Thread.sleep(10000);
}

Compile time error: unreportedException Java lang


java InterruptedException must be caught or
declared to be terminated

19 | P a g e
In this above program if we remove at lest one throws statement then the code
will not compile.

Conclusion:

We can use delegate responsibility of exception handling the caller


(it may be method or JVM)

It is required only for checked exception and uses of


throws keywords for unchecked exception there is no
impact.

Throws clause
Or
keywords

If is required only to convince compiler and usage of


throws keyword doesn’t prevent abnormal termination

Note: it is recommended to use try catch over


throws keywords.

20 | P a g e
Case1:

We can use throws keyword for method and constructor but not for class.
public class testcase throws Exception { //invalid
testcase()throws Exception //valid
{
public void m1()throwsExcption; //valid

}
Case 2:

We can use throws keyword only for throwable type of we are trying to use
for normal java class then we will get compile time error saying incompatible
type.
public class demoo {
public void m1()throws demoo {

}
Compile time error:
Incompatible type found test found :test required java.lang throwable
Case3:
public class demoo { public class demoo {
public static void public static void main(String[]
main(String[] args) { args) {
throw new throw new Error(); //unchecked
Exception(); }
}
}
} Exception in thread "main"
Unresolved compilation problem: java.lang.Error
Unhandled exception type at
Exception excelr/Tulalu.demoo.main(demoo.java:5)

Case 4:
public class Teest {
public static void main(String[] args) {
try {
System.out.println("hello");
}
catch(Exception e) {
//partially_unchecked
}
}
}
Valid
//output:
// hello

21 | P a g e
public class Teest {
public static void main(String[] args) {
try {
System.out.println("hello");
}
catch(ArithmeticException e) {
//unchecked
}
}
}
o/p: hello

public class Teest {


public static void main(String[] args) {
try {
System.out.println("hello");
}
catch(InteruptedException e) {
//fully checked
}
}
}
Exception java.lang ie is never thrown in body corresponding try statement

public class Teest {


public static void main(String[] args) {
try {
System.out.println("hello");
}
catch(IoException e) {
//fully checked
}
}
}
Exception java.lang io exception is never thrown in body of crossponding
try statement

public class Teest {


public static void main(String[] args) {
try {
System.out.println("hello");
}
catch(Error e) {
//unchecked
}
}
}
o/p
hello

22 | P a g e
with in the try block if there is no chance of raising an exception then we
shouldn’t write the catch block for that exception other wise compile time error
saying xxx never thrown in body of corresponding try statement, but this rule
applicaqble only for fully checked exception.

Exception handling keywords summary:

1> Try:- to maintain risky code.


2> Catch:- to maintain exception handling code.
3> Finally:- to maintain cleanup code.
4> Throw:- to handover our created exception object to the JVM manually.
5> Throws:- to delegate responsibility of exception handling to the caller.

Various possible compile time Error I Exception handling:

1> Unreported Exception xxx: must be caught or declared to be thrown.


2> Exception xxx has already been caught.
3> Exception xxx is never thrown in a body of corresponding try statement.
4> Unreachable statement.
5> Incompatible types
➢ Found : test
➢ Required : java.lang.throwable
6> Try without catch or finally
7> Catch without try
8> Finally without try

Customized or user defined Exception:

Sometimes to meet programming requirement we can define our own exceptions


such type of exception is called as customized or user defined exception.

Import java.util.scanner;

Class TooYoungException Extends RuntimeException{

TooYoung Exception(String s){

Super(s)→to make description available to default exception handler

Too old Exception extends RuntimeException{

toooldException (String s){

super(s)-→ defining customized exception

}]
23 | P a g e
package Tulalu;

import java.util.Scanner;

public class classcastexception {


public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int age=Integer.parseInt(args[0]);
if (age<(60) {
throw new TooyoungException("pless wait sometime ..you
will get best match");
}
else if (age>18) {
throw new ToOldException("you are age is alarday crosed
marrige age --- no chance to getting marrid");
}

else {
System.out.println("you will get matched details send by
mail");
}
}
}

Top 10 Exceptions:

Based on the person who is raising an exception are divide into two categories:

➢ JVM Exception
➢ ProgrammaticException

JVM Exception:

The exception which are raised automatically by JVM whenever a particular


event occurs are called JVM exception.

 Arithmetic Exception
 NullPointer Exception

Programmatic Exception:

The Exception which are raised explicitly by programmer or by API developer


to indicate the something wrong are called programmatic Exception.

 TooOldException
 IllegalArgumentException

24 | P a g e
1>ArrayIndexOutOfBoundException:

It is a child class of RuntimeException & it is unchecked.

Raised automatically by JVM whenever we are trying to access array element


without of range index.
public class Arrayindexoutofbound {
public static void main(String[] args) {
int[]x=new int[4];
System.out.println(x[0]);
System.out.println(x[10]);// r.e saying outofbound/range
}
}
2>NullPointer Exception

It is a child class of RuntimeException & it is unchecked.

Raised automatically by JVM whenever we are trying to perform ant operation


on null
public class nullpointer {
public static void main(String[] args) {
String s=null;
System.out.println(s.length());
}

}
Output:
NullPointerException
3>ClassCastException

It is a child class RuntimeException & it is Checked

Raised automatically by JVM whenever we are trying to type cast parent obj to
child type.
public class classcast {
public static void main(String[] args) {
// String s=new String("tulalu");
// object o=new object();
object o=new object();
String s=(String)o;
}
}
Class cast exception
4>StackoverflowError.

It is the child class or error & then it is unchecked

Raised automatically by JVM ,whenever we are trying to perform recursive


method call.

25 | P a g e
public class stackoverflowerror {
public static void m1() {
m2();
}

public static void m2() {


m1();

}
public static void main(String[] args) {
m1();
}
Output:
Runtime Exception saying StackoverflowError

5>No class Definition found Exception:

It is the child class of error & hence it is unchecked.

Raised automatically by JVM ,whenever JVM unable to find required


classFile.[java test+ enter]

It test class file is not available then we will get runtime exception saying
NoclassException.

6> ExceptionInInitializerError:

It is the child class of error & hence it is unchecked

Raised automatically by JVM if any exception occurs while executing static


variable assignments & static block
public class exceptioninintilizer {
public static void main(String[] args) {
Static int x=10/0;
}

}
Exception thread main java.lang.exception on intntialtilizerError caused by
javala.lang Aritmatic error / by zero

public class exceptioninintilizer {


static {
String s=null;
System.out.println(s.length());
}
public static void main(String[] args) {
// Static int x=10/0;
}

}
Re saying null pointer exception

26 | P a g e
7>IllegalArgumentException:

It is the child class of RuntimeException & it is unchecked

Raised automatically by programmer or by API developer indicate that a method


has been invoked with illegalArugmement
public class illigalearugment {
public static void main(String[] args) {
Thread t=new Thread();
t.setPriority(5);
t.setPriority(10);
}

}
Re saying illegalArugmentException
8>NumberFormateException:

It is the child class of IlligalArugmentException which is child class.

Raised explicitly by eaither programmer or API developer to indicate that we


are converting string to number & string is not property formatted.
public class numberformated {
public static void main(String[] args) {
int x=Integer.parseInt("10");//j.l number formatedException
int i=Integer.parseInt("ten");
}
}
9>IllegalThreadException

It is the child class of runtime Exception & it is unchecked.

Raised Explicitly by eaithe programmer of API developer to indicated that a


method has been invoked at wrongtime
public class illigalethread {
public static void main(String[] args) {
Thread t=new Thread();
t.start();
t.start();
}
}
Illegalthreadstate Exception
After starting of a thread we are not allowed to restart the same thread once
again otherwise we will get Re saying IllegalThreadState Exception.

10>AssertionError:

It is a child class of Error & it is unchecked.

Raised automatically by the programmer or by API developer to indicate that


assert statement fails.

27 | P a g e
Example:

Assert(x<);

If x is not grater then 10 then we will get re saying Assertion Error.

 ArrayindexoutoFBoundException
 NullPointerException
 ClassCastException Raised automatically by JVM exception &
 Stack overflow error there are JVM exception
 noclassdefException
 exceptioninitializerError

 illegalArgumentException
 NumberfromateException
Raised Explicitly eaither by programmer or by API
 IllgalThreadstateException developer & hence these are programmatic
 AssertionError execption

1.7 Enhancement with respect to exception handling:

As a part of 1.7 version enhancement in exception handling the following two


concepts are introduced.

 Try with resources


 Multi catch block

Try with resources:

Until 1.6 version it is highly recommend to write finally block to close


resources which are opened as a part of try block.

1.7 version

Try(Br br=new BR(newFR(“input.txt”))){

//use br base on our requirements

28 | P a g e
Conclusions:

We can declare multiple resources but these resources should be separated


with.

Try(r1;r2;r3)

Try(filewriter fw=new filewriter(“lutput.txt”);-→r1

Fr fr=new fr(“input.txt”)){-→ r2

All resources should be “Auto closable” resources

Resouces are said to be auto closeable if & only if corresponding classes


implements java.lang,interface .

All IO resources ,database, related resources & network related resources are
already implemented auto closeable interface.

Auto closeable interface came in 1.7v & contains only one method i.e close().

Public void close()

Try(r1;r2;r3){

➢ Auto closeable
➢ Java .lang .Auto closeable
➢ 1.7 version
➢ Close ()

All resources reference variable are implicitly final & hence with in the try
block we cant perform reassignment otherwise we will get CE.

Import java.io.*;

Public class demo{

Main(){

Try(BufferReader br=new BufferReader(new fileReader(“input.txt”)){

Br=new BufferReader(new FileReade(“output.txt”));

} //ce: Auto-closeable resources br may not be assigned

29 | P a g e
Until,1.6 version try should be associated with either catch or finally but from
1.7 version onwards we can take only try without catch or finally.

Catch or finally

Try(R){

------

-----

The main advantage of try with resources is we are required to write finally
blocks explicitly because we are not required to close resources explicitly until
1.6 v finally block will be like hero but 1.7 version onwards it becomes zero.

Multi catch block:

Until 1.6 even thought multiple different exceptions having same handling code
for every exception type we have to write a separate catch block it increases
length of the code & reduced readability.

Try{-----}

Catch(AE e){

e.printStackTrace();

Catch(io Exception e){

e.printStackTrace();

Catch (NPE e){

Sop(e.getMessage));

Catch(interuptedException e)

Sop(e.getMessage());

30 | P a g e
To overcome these problem sun people introduced multi catch block in 1.7
version according to this we can write a single catch block that can handle
multiple different types of exceptions.

Try{

----

Catch(AE/io exception e)

e.printStackTrace();

Catch(NPE /InterruptedException e){

Sop(e.getmessage());

The main advantages of this approach is length of code will be reduced &
readability of the code will be increased.
public class multicatch {
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);

}
}

}
In the above example wither raised exception is either ArithmeticException or
NPE the same catch block can respond in multi-catch block there shouldn’t be
any relation between exception type either child to parent or parent to child or
same type otherwise we will get compile time error.
try {
//statenment
}
catch(ArithmeticException |Exception e) {

31 | P a g e
Exception propagation:

In side a method if an Exception raised and if we are not handling that


exception object will be propagated to caller then caller method is responsible
to handle exception this process is called exception propagation.

m1(){

m2(){

Rethought Exception:

We can use this approach to convert one exception type to another exception
type.
public class rethroug {
public static void main(String[] args) {
try {
System.out.println(10/0);
}
catch(ArithmeticException e) {
throw new NullPointerException();

}
}
}
Error:
Exception in thread "main" java.lang.NullPointerException
at excelr/exception_types.rethroug.main(rethroug.java:9)

32 | P a g e

You might also like