The document provides an overview of exception handling in Java, explaining the types of exceptions (checked and unchecked) and the structure of try-catch-finally blocks. It outlines rules for writing these blocks, common exceptions, and the use of the throw and throws keywords. Additionally, it discusses the try-with-resources feature introduced in Java 7 for automatic resource management.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0 ratings0% found this document useful (0 votes)
6 views1 page
Exceptions
The document provides an overview of exception handling in Java, explaining the types of exceptions (checked and unchecked) and the structure of try-catch-finally blocks. It outlines rules for writing these blocks, common exceptions, and the use of the throw and throws keywords. Additionally, it discusses the try-with-resources feature introduced in Java 7 for automatic resource management.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 1
Java Exception Handling Cheat Sheet
Gavaconceptoftheday.com)
Basics
Types Of Exceptions
What is exception?
Exception is an abnormal condition which ocours
during execution ofa program and disrupts the
hormalfiow of 9 program
Ex: NumberFomatException, WithmaticBxcoation,
‘rtayindexoutowoundsexcoption,
Classcastexception, ulainterexception,
StackOverlowezror, OutorMemoryerror et
Exception Handling tn Java:
Exceptions in Java are handled using try, catch and
finally biock.
wy
‘This block contains statements which may
throw oxcoptionsduriag runtime,
t
atehExcoption &)
t
“hie blocchandles the exceptions thrown by the
uy black
x
‘nally
‘Thic blockie always executed whether an
exception I thrown or not and thrown exception
Is caught ornet,
+
Rules To Follow While Writing try-catch-finally
Blocks :
by, catch and finally blocks form one.
‘There mustbe one try blockand one or more
catch blocks. fray block is optional
There should not be any statements in betweon
the blocks,
IT there are multiple catch blocks the order of
catch blocks must be from most specie ro
general ones-Le.lower cassesin ne hierarchy
ff exceptions must comets and higher
classes later.
i ty-cateh-fnaly blocks are supposedto retum =
vale
¥- sHfnally block oturns a value then try and
catch blocks may ormay notretum a value.
¥ tHfinally block does not return a value then
both try and catch blocks must return a value.
¥ Thaly block overrides return valuestrom ty
land catch blocks.
¥ Thaly blockwil be aluays executed even
‘ough ey and ath Blocks ae returing the
onal
There are two types of exceptions h Java
1. Checked Exceptions are the exceptions which are checked during compilation sel
2. Unchecked Excoptions are the excoptions which are not checked during compilation. They occur
only at runtime:
Checked Exceptions
Unchecked Exceptions
“They are checked at comple time.
“They are not checked at comple He
“They af comple time exceptions.
“They are run ime exceptions
“These exceptions mist be handled propery eRher
using try-catch blocks or using throws clause,
otherwise compiler wilthrow error
these exceptionsare not nandled properly,
compier wil not throw any error. But, you may get
frrorat run time
TA the sub asses ofjavalana.Sxcepton (except
sub classes of javalang.RunTimeException) are
TAU the sub asses of java lang. Run imeExcepton
and all the sub classes of javaang.Evrr ere
checked exceptions, iinchecked exceptions
Ex: FleNotroundexcepton, 1OEwception, Ex : Mullpcinterexceotion,Arthmeticexception,
SSOLExcoptin, CasstotFoundexception Classcastexcopton,
SrrayladexOutOWBoundsExcepton
Hierarchy Of Exceptions
Javallang.Throwable is the super class forall type of errors and exceptlonsin ava,
thas two sub classes
1. javalang.Error :Itis the superclass forall types of erors in eva
2 javaslang.excoption : [isthe superclass forall types of exceptions in Java
throw Keyword throws Keyword
Frequently Occurring Except
+1) NullPointerException occurs when your
‘application tiesto access nul object
2) arrayindexoutofsoundsexception occurs
tunen you try to access an array lemant with an
Invalid Index ie index greaterthan the array length
or witha negative index
3) NumberFormatException is thrown when you
are tiving to convert a sting to numeric value ike
Integer, Toat, double etc... but input string s nota
val number
4) ClassNotFoundexception is thrown when an
application tries to load a class at runtime but the
Class with spectied name isnot found in the
classpath.
5) ArithmeticException is thrown when an
jbnormal arithmetic condition arises an
‘application
{6) SQLException is thrown when an application
encounters with an errorwhile interacting with the
database,
7) ClassCastexception occurs nhien an object of
fone type can notbe castedte ancther type.
£8) 10Exception occurs when an [0 operation fais
in your application
9) NoClassDefFoundérror is thrown when Java
Funtime System tles to load the definition ofa
class which s no longer avaiable.
10) StackOverflowError isa runtime error which
foccurs when stack overfions. This happens when
Yyoukeep caling the methods recusively.
throw keywordis used te throw an exception throws keynordis used to specify the exceptionsthat
expletiy. maybe thrown bythe method
ww roturn_typ8 method_nama(earameter fet throws
c txception fet
throw InstanceotThrowableType; ‘
> some statements
éatch(InstanceOtThrowableType) >
‘ where, exception listis the list of exceptions that
5 tmothod may throw. Exceptions must be separated by
where, InstanceOrThrowabletype must be an object
of type Throwable or subclass of Throwable.
Try-with Resources
Ty with resources blocks are introduced from lava 7. in these Blocks, resources used In try blocks are auto-
closed. No need to clase the resources explicitly. But, Java 7 ty with resources has one drawback. tt requlras
resources to be declared locally within try block It doesnt recognize resources declared outside the try block.
That issue has been resolved in lava 9
Before Java? After Java 7
[Mbednerecuashee
After Java
‘w{DelareesucesharOR ELSE se al
verte celta cede)
idee rescoerhere
wy t yas erence dedaredrescuces
( Msereseces bare hare)
Moaresoscestore } i
cath epton) Mreacstore
cach xceptone t ’
( Moree bret cach (Exipone)
{escrecestns trea ! q
) ‘Meech oy
fea {Reucsereseo deed )
‘ [Nori om recs expt
Woe cescstece Rescue noced
i {None toca rece epy