0% found this document useful (0 votes)
4 views

Exception

Uploaded by

saqlaindange27
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Exception

Uploaded by

saqlaindange27
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Exception : An unexcepted unwanted event that distrubs normal flow of program is

called Exception
- It is highly recommended to handle Exceptions and the main objective of Exception
Hnadling is graceful termination of the program
-
Exception Handling : Exceptio Hndling doesn't mean repairing an exception we have
to provide alternative way to continue rest of the program normally is a concept of
Exception Hnadling

RunTime Stack Mechanism : - ?

-inside a method if a exception occurs the method in which it is rised is


responsible to create a exception object by including the following information :
Name of exception,description of exception and location at which exception occurs.
-After creating exception object method handovers that object to the JVM
-JVM will check wheather the method contains any exception handling code or not if
the method dosdmt contain exception handling code then JVM terminates that method
abnormally and removes the corresponding entry from the stack
-then JVM identifies caller method and checks wheather caller emthod contains any
handling code or not
-If caller method dosnt contain handling code then JVM terminates that caller
method also abnormally and removes the coresponding entry from the stack
=this process will be continued until main method and if the main method also
doesnt contain handling code then JVm terminates main method abnormally and removes
corresponding entry from the stack
-then JVM handovers responsibility of exception handling to defaulf exception
handler, which is the part of JVM
-Default exception handler prints exception information in the following format and
terminates program abnormally
-Format : Exception in thread main" : name of exception : description Stck Trace

Throwable class : -Throwable class access root for java exception hierarchey
-Throwable class defines two child classes 1) Exception 2) Error

Exception : Most of the times Exceptions are caused by our program and these are
recoverable

Error : Most of the times errors are not caused by our program and these are due to
lack of system resources. Errors are non-recoverable

Checked Exceptions :exception which are checked by compiler for smooth execution of
program at run time
-In our program if there is a chance of rising checked exception then compulsory we
should handle that checked exception (either my try/catch or throws keyword)
otherwise we wll get compile time error
-Example : FileeNotFoundException,Halllticketnotfoundexception,penforgotexception
etc..
-Types
1)Fullychecked : A checked exception is said to be fully checked if and only if all
its child classes also checked
Example : IOExpeption,InteruptedException

2)PartiallyChecked : A checked exception is said to be partially checked if and


only if some of its child classes are unchecked
Example : Exception,Throwable
Note : the only possible partially checked exception is java are
Exception,Throwable

Unchecked Exceptions : the exceptions which are not checked by compiler wheather
programmer handling it or not such types of exceptions are called unchecked
exceptions
-Example : ArthematicExcepton, GasBlastexception etc.

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


there is no chnace of occuring any exception at compile time

Note: -RE and its child classes,Errors and its child classes are unchecked expect
remainning are checked Exception (pleaserefere diagram durgajava 46:00 )

................................................................................
Customized Exception Hndling using try-Catch :

-Note : a code which may cause exception is called risky code and we have to define
that code inside try block and the corresponding handling code we have to define
inside catch block

-Example : Control flow in try-catch


try
{
stmt1;
stmt2;
stmt3;
}
catch()
{
stmt 4;
}
stmt 5;

case 1: if exception occurs at stmt 2 and corresponding catch block match :- 1,4,5
statement will execute
Note : within the try block if anywhere an exception rised then rest of the try
block wont be executed when though we handled that exception hence within the try
block we have take only risky code and the try block should be as less as possible

case 2: if exception occurs at stmt 2 and corresponding catch block not match :- 1
statement will execute (Abnormal termination)
case 3: if exception occurs at stmt 4 or 5 then it is always abnormal termination

-Methods to print Exception Infomation (present in Throwable Class):


-1)printStackTrace() : prints Name of Exception,Description of exception and stack
trace
2)SOP(e); or SOP(e.toString()) : -prints Name of Exception,Description of exception
3)getMessage() :-prints only Description
Note : internally DefaultExceptionHandler uses printStackTrace()

-try with multiple catch blocks :


Note : if try with multiplr catch block present then the order of catch block is
very important we have to take child first and then parent otherwise we will get
compile time error saying : Exception XXX has already been caught
Note : JVM alway executes catch block from top to bottom

Example 1: will give compile time error saying CE :Exception java.lanag.AE has
already been caught
try
{
risky code
}
catch(Exception e)
{
}
catch(ArthemeticException e)
{
}

..........................................................
final : -final is the modifier applicable for classes methods and variables
-if a class declared as final then we cannot extend that class
-if a method declared as final we cannot override that method in the child class
-if a variable declared has final then we cannot perform reassignment for that
variable

finally : -it is a block always associated with the try-catch to maintain cleanup
code
-the speciality of finally block is it will be executed always irrespective of
wether exception rises or not wether it is handled or not but finally always
execute

finalize() :- finalize is a method always invoked by GC just before destroying an


object to perform cleanup activities
-once finalize method completes immediately GC destroys that object

Q.Defference between finally block and finalize() methoed cleanup activity


->finally block is responsible to perform cleanup activities related to try block
i.e whatever resource we opned as a part of try-block will be closed inside finally
block
->finalize() method is responsible to perform cleanup activities related to Object
i.e whatever resources associated with the object will be delocated before
desroying an object by using finalize()

...................................................................................
...............................
Example : possible try,catch and finally block combinations
-ex1 : // CE: try without catch or finally
try
{
}
.....
ex2: //CE :catch without try
catch()
{
}
......
ex3 :
finally
{
}
......

ex4: CE : caatch without try


try{
}
finally
{
}
catch()
{
}
.......
ex5: //CE : try without catch or finally and CE : catch without try
try
{
}
SOP("'hello)
catch()
{
}
........................
ex6: CE : catch without try
try
{
}
catch()
{
}
SOP("hi")
catch()
{
}

....................
ex7 ://CE: finally without try
try
{
}
catch()
{
}
SOP("hi")
finally
{
}

..........................................
ex8 : // no problem in this code
try
{
try
{
}
catch()
{
}
}
catch()
{
}

,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

ex9 : CE : // try without catch or finally


try
{
try
{
}

}
catch()
{
}

..............................
ex10 : No problem
try
{
try
{
}
fiannly
{
}
}
catch()
{
}

........................................
ex11 : no problem
try
{
}
catch()
{
try
{
}
finally
{
}
}

................................
ex12 : CE : finally without try
try
{
}
catch(0
{
finally
{
}
}

..............................................
ex13 : No problem
try
{
}
catch()
{
}
finally
{
try
{
}
catch()
{
}
}

...............................
ex14: CE : finallywithout try

try
{
}
catch()
{
}
finally
{
finally
{
}
}
...............................................
ex15 : CE : for each and every try,catch and finally block curly brackets are
required even if there is single statment present
try
SOP("hu");
catch()
{
SOP("hi");
}
finally
{
}

........................................................
throw keyword :- Sometimes we can create Exception object explcitly and we can
handover to the JVM manually for this we have to use throw keyword
-(using thorw handover our created exception object to the JVM manually)throw new
= AE("/ by zero") : here created AE object explicitly
-hence the main objective of throw keyword is to handover our created exception
object to the JVM manually instead of default exception handler
-visit 17:30 part 5 for program
-best use of throw keyword is for user defined exceptions
-examples
1)case 1 : //RE : saying AE
class Test
{
static AE a = new AE();
P S V M()
{
throw e;
}
}

2)case 2 : //RE : NPE because e references Null value


class Test
{
static AE e;
P S V M()
{
throw e;
}
}

3)case 3 : will give AE at runtime but wont give any compile time error
class Test
{
p s v m()
{
SOP("10/0")
SOP("Hello");
}}

4)case 4 : will give CE saying unreachable statement because we cannot right any
statement after thow keyword
class Test
{
p s v m()
{
throw e
AE e = new AE("/ by zero")
SOP("Hello"); //here look
}}

case 5: throw keyword only be used with throwable object so here we will get CE:
incompatible types found

class Test
{
p s v m(String[] args)
{
throw new Test();
}
}

case 6: //RE : exception in thread main" Test because Test object is now throwable
object
class Test extends RuntimeException
{
p s v m(String[] args)
{
throw new Test();
}
}

...................................................................................
......................

throws keyword : -in our program if there is a posssibility of rising checked


exception then compulsory we should hndle that check exception otherwise we will
get CE : unreported exception XXX: must be caugh or declared with thrown
-we can use throws keyword to delegate resposibility of Exception handling to the
caller(it maybe another method or JVM) then caller method is responsible to handle
that exception
-throws keyword required only for checked exceptions and usage of thowrs keyword
for unchecked exceptions there is no use or impact
-throws keyword required only to convince compiler and usage of throw keyword dosnt
prevent abnormal termination of the program

-Example1:// CE : unreported exception XXX: must be caugh or declared with throw


class Test
{
p s v m()
{
Printer pw = new PrintWriter("abc.txt")
pw.println("Hello");
}
}

-Example 2 :// CE : unreported exception java.lang.InterruptedException: must be


caught or declared to be thrown
class Test
{
p s v m()
{
Thread.sleep(1000);
}
}
..........
Note : whenever we are using sleep() method of thread class which is also checked
exception
..........

-we can handle this Example 1 & 2 CE my following 2 ways:


Example 1 : by using try-catch
class Test
{
p s v m()
{
try {
Thread.sleep(1000);
}
catch(InterruptedException e)
{
}
}
}

Example 2 : by using throws keyword


class Test thowrs InterruptedException
{
p s v m()
{
Thread.sleep(1000);
}
}

Example 3 : In above example if we remove any one throws statement then the code
wont compile CE : unreported exception
class Test
{
p s v m () thows IE
{
doStuff();
}
public void doStuff()thows IE
{
domoreStuff();
}
public void domoreStuff() thows IE
{
Thread.sleep(1000)
}
...................................................................................
............................

Examples and cases of throws keyword :

-case 1 : we can use throws keyword for methods and constructors but not for
classes
class Test throws Exception //not possible will get CE
{
test() throws Exception
{
}
public void m1() throws Exception
{
}
}

--case 2 : throws keyword only for throwable types if we are tryig to use for
normal java classes then we will get CE : incompatible types
class test
{
public void m1() throws Test
{
}
}

--case 3 : //will compile and execute now


class test extends RuntimeException
{
public void m1() throws Test
{
}
}

...................................................................................
.................

some example cases on throw keyword :

-Example 1 : // CE : unreported exception java.lang.exception must ib caught or


declared to be thrown

class Test
{
p s v m()
{
throw new Exception();
}
}

-Example 2 : //RE : exception in thread main java.lang.erroe at Test.main()

class Test
{
p s v m()
{
throw new Error();
}
}
...................................................................................
.................

cases with example we should understand :

-case 1 : //compiles fine


class Test
{
p s v m()
{
try {
sop("Hello")
}
catch(AE e)
{
}
}
}

-case 2 : //compiles fine


class Test
{
p s v m()
{
try {
sop("Hello")
}
catch(Exception e)
{
}
}
}

-case 3 : CE :
class Test
{
p s v m()
{
try {
sop("Hello")
}
catch(IOException e)
{
}
}
}
-case 4 : // CE :
class Test
{
p s v m()
{
try {
sop("Hello")
}
catch(InterruptedException e)
{
}
}
}

-case 5 : //compiles fine


class Test
{
p s v m()
{
try {
sop("Hello")
}
catch(Error e)
{
}
}
}

Note : witin a try block if there is no chnace in rising a exception then we can't
right catch block for that exception otherwise we will compile time error saying :
Exception XXX is never thrown in body of corresponding try statement
Note but above mentioned rule is applicale only for fullychecked exceptions

................................................................
Customized Exception :Sometimes to meet the programming requirmnets we can define
our own exceptions such types of exceptions are called customized or user defined
exceptions

Example :
class TooOldException extends RuntimeException
{
TooOldException(String s)
{
super(s); //to make description available to default exception handler
}
}

throw keyword is best suitable for user defined exception but not for pre-defined
exceptions
Note : Highly recomended to define customized as unchecked that is we have to
extends RuntimeException but not Exception
Note : super() we use this because to pass string to parent throwable class where
printstacktrace method is present

...................................................................................
........

Top 10 Exceptions :-based on person who is rising an exception all exceptions are
divided into 2 types

1)JVM Exceptions :- the exceptions which are rised automatically by JVM whenever a
particular event occurs are called JVM exception e.g AE,NPE,etc

2)Programmatic Exceptions : the exceptions which are rised explicitly either by


programmer or by API developer to indicate that something goes wrong are called
programmatic exceptions
-example : TooOldExceptions,IllegalArgument Exception etc

Top 10 java exceptions:

1)ArrayIndexOutOfBoundException : it is a child class of RuntimeException and hence


it is unchecked rised automatically by JVM whebever we are trying to access Array
element which out of range index

2)NullPointerException : it is a child class of RuntimeException and hence it is


unchecked rised automatically by JVM whebever we are trying to pefrom any operation
on Null

3)ClassCastException : it is a child class of RuntimeException and hence it is


unchecked rised automatically by JVM whenever we are trying to type cast parent
object to child type
ex 1 : Object o = new Object();
String s = (String)o //RE : CCE

ex2 : Object o = new String("hi");


String s = (String)o // well perform well

4)StackOverFlowError : it is a child class of Error hence it is unchecked rised


automatically by JVM whenever we are trying to perform recursive method call
ex : clas test
{
p s v m1()
{
m2();
}
p s v m2()
{
m1();
}
ps v m()
{
m1();
}
}

Note : for every thread call JVM creates runtime stack

5) NoClassDefFoundError : it is a child class of Error hence it is unchecked rised


automatically by JVM whenever JVM unable to find required .class file

6)ExceptionInInitializerError : it is a child class of Error and hence it is


unchecked rised automatically by JVM if any exception occurs while executing static
variable assignmenets and the static blocks
ex : class Test //ExceptionInInitializerError caused by : java.lang.AE
{
static int x=10/0;}

ex2: class test //ExceptionInInitializerError caused by : java.lang.NPE


{
static
{
String s=null;
SOP(s.lenght());
}
}

7)Illegal

...................................................

Only one video is remaining for exceptions

You might also like