Вы находитесь на странице: 1из 15

ContentMenu

Elite Creations What is the difference between checked and unchecked


exceptions?

ExceptionHandlinginJava Whathappensbehindthecodeintdata=50/0?

Whyusemultiplecatchblock?
Theexceptionhandlinginjavaisoneofthepowerfulmechanism to
Isthereanypossibilitywhenfinallyblockisnotexecuted?
handle the runtime errors so that normal flow of the application can
Whatisexceptionpropagation?
bemaintained.
Whatisthedifferencebetweenthrowandthrowskeyword?
In this page, we will learn about java exception, its type and the
What are the 4 rules for using exception handling with method
differencebetweencheckedanduncheckedexceptions.
overriding?

Whatisexception
HierarchyofJavaExceptionclasses
DictionaryMeaning:Exceptionisanabnormalcondition.

In java, exception is an event that disrupts the normal flow of the


program.Itisanobjectwhichisthrownatruntime.

Whatisexceptionhandling
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFound,IO,SQL,Remoteetc.

AdvantageofExceptionHandling

The core advantage of exception handling is tomaintainthenormal


flowoftheapplication. Exception normally disrupts the normal flow
of the application that is why we use exception handling. Let's take a
scenario:

1. statement1

2. statement2

3. statement3

4. statement4

5. statement5//exceptionoccurs TypesofException
6. statement6
There are mainly two types of exceptions: checked and unchecked
7. statement7
where error is considered as unchecked exception. The sun
8. statement8
microsystemsaystherearethreetypesofexceptions:
9. statement9

10. statement10 1.CheckedException

2.UncheckedException
Suppose there is 10 statements in your program and there occurs an 3.Error
exception at statement 5, rest of the code will not be executed i.e.
statement6to10willnotrun.Ifweperformexceptionhandling,rest
of the statement will be executed. That is why we use exception Difference between checked and
handlinginjava.
uncheckedexceptions
1)CheckedException
DoYouKnow?

Page 1 of 15
TheclassesthatextendThrowableclassexceptRuntimeExceptionand 1. inta[]=newint[5]
Errorareknownascheckedexceptionse.g.IOException,SQLException
Elite Creations 2. a[10]=50//ArrayIndexOutOfBoundsException
etc.Checkedexceptionsarecheckedatcompiletime.

2)UncheckedException
JavaExceptionHandlingKeywords
The classes that extend RuntimeException are known as unchecked
Thereare5keywordsusedinjavaexceptionhandling.
exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not 1.try
checkedatcompiletimerathertheyarecheckedatruntime.
2.catch

3)Error 3.finally

4.throw
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
5.throws
AssertionErroretc.

Commonscenarioswhereexceptionsmay prev next


occur
Share 84
There are given some scenarios where unchecked exceptions can
occur.Theyareasfollows:

1)ScenariowhereArithmeticExceptionoccurs

Ifwedivideanynumberbyzero,thereoccursanArithmeticException.

1. inta=50/0//ArithmeticException

2)ScenariowhereNullPointerExceptionoccurs

Ifwehavenullvalueinanyvariable,performinganyoperationbythe
variableoccursanNullPointerException.

1. Strings=null

2. System.out.println(s.length())//NullPointerException

3)ScenariowhereNumberFormatExceptionoccurs

The wrong formatting of any value, may occur


NumberFormatException. Suppose I have a string variable that have
characters, converting this variable into digit will occur
NumberFormatException.

1. Strings="abc"

2. inti=Integer.parseInt(s)//NumberFormatException

4) Scenario where ArrayIndexOutOfBoundsException


occurs

If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsExceptionasshownbelow:

Page 2 of 15
ContentMenu There can be 100 lines of code after exception. So all the code after
Elite Creations exceptionwillnotbeexecuted.

Javatrycatch
Solutionbyexceptionhandling
Javatryblock Let'sseethesolutionofaboveproblembyjavatrycatchblock.

Java try block is used to enclose the code that might throw an 1. publicclassTesttrycatch2{
exception.Itmustbeusedwithinthemethod. 2. publicstaticvoidmain(Stringargs[]){

Javatryblockmustbefollowedbyeithercatchorfinallyblock. 3. try{

4. intdata=50/0
Syntaxofjavatrycatch 5. }catch(ArithmeticExceptione){System.out.println(e)}

6. System.out.println("restofthecode...")

1. try{ 7. }

2. //codethatmaythrowexception 8. }

3. }catch(Exception_class_Nameref){}
TestitNow

Output:
Syntaxoftryfinallyblock

Exceptioninthreadmainjava.lang.ArithmeticException:/byzero
1. try{ restofthecode...
2. //codethatmaythrowexception

3. }finally{} Now,asdisplayedintheaboveexample,restofthecodeisexecuted
i.e.restofthecode...statementisprinted.

Javacatchblock
Internalworkingofjavatrycatchblock
JavacatchblockisusedtohandletheException.Itmustbeusedafter
thetryblockonly.

Youcanusemultiplecatchblockwithasingletry.

Problemwithoutexceptionhandling
Let'strytounderstandtheproblemifwedon'tusetrycatchblock.

1. publicclassTesttrycatch1{

2. publicstaticvoidmain(Stringargs[]){

3. intdata=50/0//maythrowexception

4. System.out.println("restofthecode...")

5. }

6. }

TestitNow The JVM firstly checks whether the exception is handled or not. If
exception is not handled, JVM provides a default exception handler
Output:
thatperformsthefollowingtasks:

Printsoutexceptiondescription.
Exceptioninthreadmainjava.lang.ArithmeticException:/byzero
Prints the stack trace (Hierarchy of methods where the
exceptionoccurred).
As displayed in the above example, rest of the code is not executed
(insuchcase,restofthecode...statementisnotprinted). Page 3 of 15 Causestheprogramtoterminate.
But if exception is handled by the application programmer, normal ContentMenu
flowoftheapplicationismaintainedi.e.restofthecodeisexecuted.
Elite Creations

Javacatchmultipleexceptions
prev next
JavaMulticatchblock
Share 22
If you have to perform different tasks at the occurrence of different
Exceptions,usejavamulticatchblock.

Let'sseeasimpleexampleofjavamulticatchblock.

1. publicclassTestMultipleCatchBlock{

2. publicstaticvoidmain(Stringargs[]){

3. try{

4. inta[]=newint[5]

5. a[5]=30/0

6. }

7. catch(ArithmeticException e)
{System.out.println("task1iscompleted")}

8. catch(ArrayIndexOutOfBoundsException e)
{System.out.println("task2completed")}

9. catch(Exception e)
{System.out.println("commontaskcompleted")}

10.

11. System.out.println("restofthecode...")

12. }

13. }

TestitNow

Output:task1completed
restofthecode...

Rule: At a time only one Exception is occured and at a time


onlyonecatchblockisexecuted.

Rule:Allcatchblocksmustbeorderedfrommostspecificto
most general i.e. catch for ArithmeticException must come
beforecatchforException.

1. classTestMultipleCatchBlock1{

2. publicstaticvoidmain(Stringargs[]){

3. try{

4. inta[]=newint[5]

5. a[5]=30/0

6. }

7. catch(Exception e)
Page 4 of 15 {System.out.println("commontaskcompleted")}
8. catch(ArithmeticException e) ContentMenu
{System.out.println("task1iscompleted")}
Elite Creations
9. catch(ArrayIndexOutOfBoundsException
{System.out.println("task2completed")}
e)
JavaNestedtryblock
10. System.out.println("restofthecode...")
Thetryblockwithinatryblockisknownasnestedtryblockinjava.
11. }

12. } Whyusenestedtryblock
TestitNow Sometimes a situation may arise where a part of a block may cause
oneerrorandtheentireblockitselfmaycauseanothererror.Insuch
Output:
cases,exceptionhandlershavetobenested.

Compiletimeerror
Syntax:

1. ....

prev next 2. try

3. {

4. statement1
Share 5
5. statement2

6. try

7. {

8. statement1

9. statement2

10. }

11. catch(Exceptione)

12. {

13. }

14. }

15. catch(Exceptione)

16. {

17. }

18. ....

Javanestedtryexample
Let'sseeasimpleexampleofjavanestedtryblock.

1. classExcep6{

2. publicstaticvoidmain(Stringargs[]){

3. try{

4. try{

5. System.out.println("goingtodivide")

6. intb=39/0

7. }catch(ArithmeticExceptione){System.out.println(e)}

8.

9. try{

10. inta[]=newint[5]

Page 5 of 15 11. a[5]=4


12. }catch(ArrayIndexOutOfBoundsException e) ContentMenu
{System.out.println(e)}
Elite Creations
13.

14. System.out.println("otherstatement)
Javafinallyblock
15. }catch(Exceptione){System.out.println("handeled")} Javafinallyblockisablockthatisusedtoexecuteimportantcode such as
16. closingconnection,streametc.

17. System.out.println("normalflow..")
Javafinallyblockisalwaysexecutedwhetherexceptionishandledornot.
18. }
Javafinallyblockfollowstryorcatchblock.
19. }

prev next

Share 11

Note:Ifyoudon'thandleexception,beforeterminatingtheprogram,
JVMexecutesfinallyblock(ifany).

Whyusejavafinally
Finallyblockinjavacanbeusedtoput"cleanup"codesuchasclosing
afile,closingconnectionetc.

UsageofJavafinally
Let'sseethedifferentcaseswherejavafinallyblockcanbeused.

Case1

Let'sseethejavafinallyexamplewhereexceptiondoesn'toccur.
Page 6 of 15
1. classTestFinallyBlock{ 7. catch(ArithmeticExceptione){System.out.println(e)}

2. publicstaticvoidmain(Stringargs[]){
Elite Creations 8. finally{System.out.println("finallyblockisalwaysexecuted")}

3. try{ 9. System.out.println("restofthecode...")

4. intdata=25/5 10. }

5. System.out.println(data) 11. }

6. }
TestitNow
7. catch(NullPointerExceptione){System.out.println(e)}

8. finally{System.out.println("finallyblockisalwaysexecuted")} Output:Exceptioninthreadmainjava.lang.ArithmeticException:/byzero
9. System.out.println("restofthecode...") finallyblockisalwaysexecuted

10. } restofthecode...

11. }

TestitNow
Rule:Foreachtryblocktherecanbezeroormorecatchblocks,but
Output:5 onlyonefinallyblock.
finallyblockisalwaysexecuted
restofthecode...
Note: The finally block will not be executed if program exits(either
by calling System.exit() or by causing a fatal error that causes the
Case2 processtoabort).

Let's see the java finally example where exception occurs and not
handled.

prev next
1. classTestFinallyBlock1{

2. publicstaticvoidmain(Stringargs[]){
Share 5
3. try{

4. intdata=25/0

5. System.out.println(data)

6. }

7. catch(NullPointerExceptione){System.out.println(e)}

8. finally{System.out.println("finallyblockisalwaysexecuted")}

9. System.out.println("restofthecode...")

10. }

11. }

TestitNow

Output:finallyblockisalwaysexecuted
Exceptioninthreadmainjava.lang.ArithmeticException:/byzero

Case3

Let'sseethejavafinallyexamplewhereexceptionoccursandhandled.

1. publicclassTestFinallyBlock2{

2. publicstaticvoidmain(Stringargs[]){

3. try{

4. intdata=25/0

5. System.out.println(data)

6. }
Page 7 of 15
ContentMenu ContentMenu
Elite Creations

Javathrowexception JavaExceptionpropagation
An exception is first thrown from the top of the stack and if it is not

Javathrowkeyword caught,itdropsdownthecallstacktothepreviousmethod,Ifnotcaught
there,theexceptionagaindropsdowntothepreviousmethod,andsoon

TheJavathrowkeywordisusedtoexplicitlythrowanexception. until they are caught or until they reach the very bottom of the call
stack.Thisiscalledexceptionpropagation.
We can throw either checked or uncheked exception in java by throw
keyword. The throw keyword is mainly used to throw custom
exception.Wewillseecustomexceptionslater. Rule: By default Unchecked Exceptions are forwarded in calling
chain(propagated).
Thesyntaxofjavathrowkeywordisgivenbelow.

ProgramofExceptionPropagation
1. throwexception
1. classTestExceptionPropagation1{
Let'sseetheexampleofthrowIOException.
2. voidm(){

3. intdata=50/0
1. thrownewIOException("sorrydeviceerror)
4. }

5. voidn(){
javathrowkeywordexample 6. m()

7. }
In this example, we have created the validate method that takes
8. voidp(){
integer value as a parameter. If the age is less than 18, we are
throwing the ArithmeticException otherwise print a message welcome 9. try{

tovote. 10. n()

11. }catch(Exceptione){System.out.println("exceptionhandled")}
1. publicclassTestThrow1{ 12. }
2. staticvoidvalidate(intage){ 13. publicstaticvoidmain(Stringargs[]){
3. if(age<18) 14. TestExceptionPropagation1obj=newTestExceptionPropagation1()
4. thrownewArithmeticException("notvalid") 15. obj.p()
5. else 16. System.out.println("normalflow...")
6. System.out.println("welcometovote") 17. }
7. } 18. }
8. publicstaticvoidmain(Stringargs[]){

9. validate(13) TestitNow

10. System.out.println("restofthecode...")
Output:exceptionhandled
11. } normalflow...
12. }

TestitNow

Output:

Exceptioninthreadmainjava.lang.ArithmeticException:notvalid

prev next

Page 8 of 15
Share 9
In the above example exception occurs in m() method where it is not ContentMenu
handled,so it is propagated to previous n() method where it is not
Elite Creations
handled,againitispropagatedtop()methodwhereexceptionishandled.
Javathrowskeyword
Exception can be handled in any method in call stack either in main()
method,p()method,n()methodorm()method. TheJavathrowskeyword is used to declare an exception. It gives an information
to the programmer that there may occur an exception so it is better for the
programmer to provide the exception handling code so that normal flow can be
Rule:Bydefault,CheckedExceptionsarenotforwardedincalling maintained.
chain(propagated).
ExceptionHandlingismainlyusedtohandlethecheckedexceptions.Ifthereoccurs
any unchecked exception such as NullPointerException, it is programmers fault that
Program which describes that checked exceptions are not
heisnotperformingcheckupbeforethecodebeingused.
propagated

1. classTestExceptionPropagation2{ Syntaxofjavathrows
2. voidm(){

3. thrownewjava.io.IOException("deviceerror")//checkedexception 1. return_typemethod_name()throwsexception_class_name{

4. } 2. //methodcode

5. voidn(){ 3. }

6. m()

7. }
Whichexceptionshouldbedeclared
8. voidp(){

9. try{ Ans)checkedexceptiononly,because:
10. n()
uncheckedException:underyourcontrolsocorrectyourcode.
11. }catch(Exceptione){System.out.println("exceptionhandeled")}
error: beyond your control e.g. you are unable to do anything if there occurs
12. }
VirtualMachineErrororStackOverflowError.
13. publicstaticvoidmain(Stringargs[]){

14. TestExceptionPropagation2obj=newTestExceptionPropagation2()

15. obj.p()
AdvantageofJavathrowskeyword
16. System.out.println("normalflow") NowCheckedExceptioncanbepropagated(forwardedincallstack).
17. }
Itprovidesinformationtothecallerofthemethodabouttheexception.
18. }

TestitNow
Javathrowsexample
Output:CompileTimeError
Let'sseetheexampleofjavathrowsclausewhichdescribesthatcheckedexceptions
canbepropagatedbythrowskeyword.

1. importjava.io.IOException
prev next
2. classTestthrows1{

3. voidm()throwsIOException{
Share 5
4. thrownewIOException("deviceerror")//checkedexception

5. }

6. voidn()throwsIOException{

7. m()

8. }

9. voidp(){

10. try{

11. n()
Page 9 of 15 12. }catch(Exceptione){System.out.println("exceptionhandled")}
13. } Case2:Youdeclaretheexception
14. publicstaticvoidmain(Stringargs[]){
Elite Creations
15. Testthrows1obj=newTestthrows1() A)Incaseyoudeclaretheexception,ifexceptiondoesnotoccur,thecodewill
beexecutedfine.
16. obj.p()
B)Incaseyoudeclaretheexceptionifexceptionoccures,anexceptionwillbe
17. System.out.println("normalflow...")
thrownatruntimebecausethrowsdoesnothandletheexception.
18. }

19. } A)Programifexceptiondoesnotoccur

TestitNow 1. importjava.io.*

2. classM{
Output:
3. voidmethod()throwsIOException{

4. System.out.println("deviceoperationperformed")
exceptionhandled
5. }
normalflow...
6. }

7. classTestthrows3{
Rule: If you are calling a method that declares an exception, you must 8. publicstaticvoidmain(Stringargs[])throwsIOException{//declareexception
eithercaughtordeclaretheexception.
9. Mm=newM()

10. m.method()
Therearetwocases:
11.
1.Case1:Youcaughttheexceptioni.e.handletheexceptionusingtry/catch.
12. System.out.println("normalflow...")
2.Case2:Youdeclaretheexceptioni.e.specifyingthrowswiththemethod.
13. }

14. }

Case1:Youhandletheexception
TestitNow

In case you handle the exception, the code will be executed fine whether
Output:deviceoperationperformed
exceptionoccursduringtheprogramornot.
normalflow...

1. importjava.io.*

2. classM{ B)Programifexceptionoccurs
3. voidmethod()throwsIOException{
1. importjava.io.*
4. thrownewIOException("deviceerror")
2. classM{
5. }
3. voidmethod()throwsIOException{
6. }
4. thrownewIOException("deviceerror")
7. publicclassTestthrows2{
5. }
8. publicstaticvoidmain(Stringargs[]){
6. }
9. try{
7. classTestthrows4{
10. Mm=newM()
8. publicstaticvoidmain(Stringargs[])throwsIOException{//declareexception
11. m.method()
9. Mm=newM()
12. }catch(Exceptione){System.out.println("exceptionhandled")}
10. m.method()
13.
11.
14. System.out.println("normalflow...")
12. System.out.println("normalflow...")
15. }
13. }
16. }
14. }
TestitNow
TestitNow
Output:exceptionhandled
normalflow... Output:RuntimeException

Page 10 of 15
Differencebetweenthrowandthrows ContentMenu
Elite Creations

Difference between throw and


Clickmefordetails

Que)Canwerethrowanexception? throwsinJava
Yes,bythrowingsameexceptionincatchblock. There are many differences between throw and throws keywords. A
listofdifferencesbetweenthrowandthrowsaregivenbelow:

No. throw throws


1) Java throw keyword is used to Java throws keyword is used
prev next
explicitlythrowanexception. todeclareanexception.

2) Checked exception cannot be Checked exception can be


Share 13
propagatedusingthrowonly. propagatedwiththrows.

3) Throw is followed by an Throwsisfollowedbyclass.


instance.

4) Throw is used within the Throws is used with the


method. methodsignature.

5) You cannot throw multiple You can declare multiple


exceptions. exceptionse.g.
public void method()throws
IOException,SQLException.

Javathrowexample

1. voidm(){

2. thrownewArithmeticException("sorry")

3. }

Javathrowsexample

1. voidm()throwsArithmeticException{

2. //methodcode

3. }

Javathrowandthrowsexample

1. voidm()throwsArithmeticException{

2. thrownewArithmeticException("sorry")

3. }

prev next

Share 7

Page 11 of 15
ContentMenu 8. System.gc()
Elite Creations 9. }}

Difference between final, finally and


finalize
prev next
Therearemanydifferencesbetweenfinal,finallyandfinalize.Alistof
differencesbetweenfinal,finallyandfinalizearegivenbelow:
Share 0

No. final finally finalize


1) Final is used to apply Finally is used Finalize is
restrictions on class, method to place used to
andvariable.Finalclasscan't important code, perform clean
be inherited, final method it will be up processing
can't be overridden and final executed just before
variable value can't be whether object is
changed. exception is garbage
handledornot. collected.

2) Finalisakeyword. Finally is a Finalize is a


block. method.

Javafinalexample

1. classFinalExample{

2. publicstaticvoidmain(String[]args){

3. finalintx=100

4. x=200//CompileTimeError

5. }}

Javafinallyexample

1. classFinallyExample{

2. publicstaticvoidmain(String[]args){

3. try{

4. intx=300

5. }catch(Exceptione){System.out.println(e)}

6. finally{System.out.println("finallyblockisexecuted")}

7. }}

Javafinalizeexample

1. classFinalizeExample{

2. publicvoidfinalize(){System.out.println("finalizecalled")}

3. publicstaticvoidmain(String[]args){

4. FinalizeExamplef1=newFinalizeExample()

5. FinalizeExamplef2=newFinalizeExample()

6. f1=null
Page 12 of 15
7. f2=null
ContentMenu 1. importjava.io.*
Elite Creations 2. classParent{

ExceptionHandling with 3. voidmsg(){System.out.println("parent")}

4. }
MethodOverridinginJava 5.

6. classTestExceptionChild1extendsParent{
There are many rules if we talk about methodoverriding with exception
7. voidmsg()throwsArithmeticException{
handling.TheRulesareasfollows:
8. System.out.println("child")
Ifthesuperclassmethoddoesnotdeclareanexception
9. }
If the superclass method does not declare an exception,
10. publicstaticvoidmain(Stringargs[]){
subclass overridden method cannot declare the checked
11. Parentp=newTestExceptionChild1()
exceptionbutitcandeclareuncheckedexception.
12. p.msg()
Ifthesuperclassmethoddeclaresanexception
13. }
If the superclass method declares an exception, subclass
overriddenmethodcandeclaresame,subclassexceptionorno 14. }

exceptionbutcannotdeclareparentexception.
TestitNow

Output:child
If the superclass method does not declare an
exception
Ifthesuperclassmethoddeclaresanexception
1) Rule: If the superclass method does not declare an exception,
subclass overridden method cannot declare the checked
1)Rule:Ifthesuperclassmethoddeclaresanexception,subclass
exception.
overridden method can declare same, subclass exception or no
exceptionbutcannotdeclareparentexception.

1. importjava.io.*

2. classParent{ Exampleincasesubclassoverriddenmethoddeclares
3. voidmsg(){System.out.println("parent")} parentexception
4. }

5. 1. importjava.io.*
6. classTestExceptionChildextendsParent{ 2. classParent{
7. voidmsg()throwsIOException{ 3. voidmsg()throwsArithmeticException{System.out.println("parent")}
8. System.out.println("TestExceptionChild") 4. }
9. } 5.
10. publicstaticvoidmain(Stringargs[]){ 6. classTestExceptionChild2extendsParent{
11. Parentp=newTestExceptionChild() 7. voidmsg()throwsException{System.out.println("child")}
12. p.msg() 8.
13. } 9. publicstaticvoidmain(Stringargs[]){
14. } 10. Parentp=newTestExceptionChild2()

11. try{
TestitNow
12. p.msg()
Output:CompileTimeError 13. }catch(Exceptione){}

14. }

15. }
2) Rule: If the superclass method does not declare an exception,
subclass overridden method cannot declare the checked TestitNow
exceptionbutcandeclareuncheckedexception.
Output:CompileTimeError
Page 13 of 15
Exampleincasesubclassoverriddenmethoddeclares Exampleincasesubclassoverriddenmethoddeclares
Elite Creations
sameexception noexception

1. importjava.io.* 1. importjava.io.*

2. classParent{ 2. classParent{

3. voidmsg()throwsException{System.out.println("parent")} 3. voidmsg()throwsException{System.out.println("parent")}

4. } 4. }

5. 5.

6. classTestExceptionChild3extendsParent{ 6. classTestExceptionChild5extendsParent{

7. voidmsg()throwsException{System.out.println("child")} 7. voidmsg(){System.out.println("child")}

8. 8.

9. publicstaticvoidmain(Stringargs[]){ 9. publicstaticvoidmain(Stringargs[]){

10. Parentp=newTestExceptionChild3() 10. Parentp=newTestExceptionChild5()

11. try{ 11. try{

12. p.msg() 12. p.msg()

13. }catch(Exceptione){} 13. }catch(Exceptione){}

14. } 14. }

15. } 15. }

TestitNow TestitNow

Output:child Output:child

Exampleincasesubclassoverriddenmethoddeclares
subclassexception prev next

1. importjava.io.* Share 12

2. classParent{

3. voidmsg()throwsException{System.out.println("parent")}

4. }

5.

6. classTestExceptionChild4extendsParent{

7. voidmsg()throwsArithmeticException{System.out.println("child")}

8.

9. publicstaticvoidmain(Stringargs[]){

10. Parentp=newTestExceptionChild4()

11. try{

12. p.msg()

13. }catch(Exceptione){}

14. }

15. }

TestitNow

Output:child

Page 14 of 15
ContentMenu
Elite Creations

JavaCustomException
If you are creating your own Exception that is known as custom
exceptionoruserdefinedexception.Javacustomexceptionsareused
tocustomizetheexceptionaccordingtouserneed.

By the help of custom exception, you can have your own exception
andmessage.

Let'sseeasimpleexampleofjavacustomexception.

1. classInvalidAgeExceptionextendsException{

2. InvalidAgeException(Strings){

3. super(s)

4. }

5. }

1. classTestCustomException1{

2.

3. staticvoidvalidate(intage)throwsInvalidAgeException{

4. if(age<18)

5. thrownewInvalidAgeException("notvalid")

6. else

7. System.out.println("welcometovote")

8. }

9.

10. publicstaticvoidmain(Stringargs[]){

11. try{

12. validate(13)

13. }catch(Exception m)
{System.out.println("Exceptionoccured:"+m)}

14.

15. System.out.println("restofthecode...")

16. }

17. }

TestitNow

Output:Exceptionoccured:InvalidAgeException:notvalid
restofthecode...

prev next

Share 2

Page 15 of 15

Вам также может понравиться