SlideShare a Scribd company logo
1 of 28
Topic 6: Exceptions
Reading: Chapter 11
Advanced Programming Techniques
Objective/Outline
• Objective: Study how to handle exceptions in java
• Outline:
– Introduction
– Java exception classes (Checked vs unchecked
exceptions)
– Dealing with exceptions
• Throwing exceptions
• Catching exceptions
Introduction
Causes of errors
User input errors:
typos, malformed URL, wrong file name, wrong info in file…
Hardware errors:
Disk full, printer out of paper or down, web page
unavailable…
Code errors:
invalid array index, bad cast, read past end of file, pop empty
stack, null object reference…
Introduction
Goals of error handling
Don’t want:
Want:
Return to a safe state and enable user to execute other
commands
Allow user to save work and terminate program
gracefully.
Introduction
• Java exception handling mechanism:
Every method is allowed to have two exit paths
– No errors occur
• Method exits in the normal way
• Returns a value
• Control passed to the calling code.
– If errors occur
• Method exits via an alternative exit path
• Throws an object that encapsulates the error information
• Control passed to exception mechanism that searches for an
appropriate exception handler to deal with the error condition
Outline
Introduction
Java exception classes
Dealing with exceptions
 Throwing exceptions
 Catching exceptions
Java Exception Classes
JVM
internal
errors
Java has many classes for error handling. They are called
exception classes
Java Exception Classes
java.io.IOExceptio
n
java.lang.VirtualMachineError
java.lang.LinkageError
java.lang.
Exception
java.lang.
Error
java.lang.
Throwable
java.lang.NullPointerException
java.lang.ArithmeticException
java.lang.RuntimeException
java.lang.ClassCastException
unchecked
unchecked
checked
java.io.EOFException…
Unchecked exceptions
Error: For internal errors in JVM.
RuntimeException: Logical errors in
program (C++ logical-error).
 Bad cast
 Out-of-bound array access
 Null reference access
Those two exceptions are unchecked
 JVM internal errors beyond your control
 You should not allow logical errors at the first place
• All other exceptions (C++ runtime_error) are
checked, i.e. you have to explicitly handle
them. Otherwise compiler errors results in.
– Trying to read pass end of file
– Open a malformed URL
– …
AclNotFoundException, ActivationException,
AWTException, BadLocationException,
ClassNotFoundException, CloneNotSupportedException,
DataFormatException, ExpandVetoException,
GeneralSecurityException, IllegalAccessException,
InstantiationException, InterruptedException,
IntrospectionException, InvocationTargetException,
Checked exceptions
Can be found in online API
Exceptions
• Typically, what methods does an exception
class have?
– Check IOException
Java Exception Classes
You can define new Exception classes.
class FileFormatException extends IOException
{ // default constructor
public FileFormatException() {}
//constructor contains a detailed message
public FileFormatException(String message)
{ super( message );
}
New Exception class must be subclass of Throwable
Most programs throw and catch objects that derive from the Exception
class
Outline
Introduction
Java exception classes
Dealing with exceptions
 Throwing exceptions
 Catching exceptions
Dealing with Exceptions
• Need to consider exceptions when writing
each method
– Identifying possible exceptions
• Check each line of code inside the method
– If a method from someone else is called, check API to see if it
throws exceptions
– If some other method you wrote is called, also check to see if
it throws exceptions.
– Dealing with exceptions
• If checked exceptions might be thrown at any point
inside the method, you need to deal with it
– Catching exceptions: Handle an exception in the current
method.
Throwing Exceptions
• Throw an exception generated by method call:
public void readData(BufferedReader in)throws IOException
{
String s = in.readLine();
StringTokenizer t = new StringTokenizer(s, "|");
name = t.nextToken();
salary = Double.parseDouble(t.nextToken());
int y = Integer.parseInt(t.nextToken());
int m = Integer.parseInt(t.nextToken());
int d = Integer.parseInt(t.nextToken());
GregorianCalendar calendar
= new GregorianCalendar(y, m - 1, d);
// GregorianCalendar uses 0 = January
hireDay = calendar.getTime();
}//DataFileTest.java from Topic 5
Throwing Exceptions
• The method readLine of
BufferedReader throws an IOExpcetion,
a checked exception
– We do not deal with this exception in the current
method. So we state that the readData method
might throw IOException.
• If you simply ignore it, compiler error results
in. Try this.
Throwing Exceptions
• Notes:
– Can throw multiple types of exceptions
public void readData(BufferedReader in)
throws IOException,
EOFException
– Overriding method in subclass cannot throw more
exceptions than corresponding method in
superclass
• If method in superclass does not throw any exceptions,
overriding method in subclass cannot either
Outline
Introduction
Java exception classes
Dealing with exceptions
 Throwing exceptions
 Catching exceptions
Catching Exceptions
Catch exceptions with try/catch block
try
{ code
more code
}
catch( ExceptionType e)
{ handler for this exception
}
If a statement in the try block throws an exception
The remaining statements in the block are skipped
Handler code inside catch block executed.
If no exceptions are thrown by codes in the try
block, the catch block is skipped.
Dealing with Exceptions
Example:
try {
average = total/count;
System.out.println(“Average is ” +
average); }
catch (ArithmeticException e) {
System.out.println(“Oops: ”+ e);
average = -1;}
If count is 0, this code will print out something like
“Oops: division by zero”.
Catching Exceptions
public static void main(String[] args)
{ try
{ BufferedReader in = new BufferedReader(
new FileReader(args[0]));
Employee[] newStaff = readData(in);
…
}
catch(IOException exception)
{ exception.printStackTrace();
}} //ExceptionTest.java
This code will exit right away with an error message if something goes
wrong in readData or in the constructor of FilerReader (an
IOException will be thrown)
Catching Multiple Exceptions
Can have multiple catchers for multiple types of exceptions:
public static void main(String[] args)
{ try
{ BufferedReader in = new BufferedReader(
new FileReader(args[0]));
Employee[] e = readData(in);
… }
catch(IOException e1)
{ exception.printStackTrace(); }
catch(ArrayIndexOutOfBoundsException e2)
{ System.out.print("No file name provided " );
System.exit(1); }
} // ExceptionTest2.java
What if GeneralSecurityException occurs in the try block?
Might throw
ArrayIndexOutOfBoundsExpection
Dealing with Exceptions
Note that the following will produce a compiling error. Why?
try {…}
catch (Exception e3) {…}
catch (ArithmeticException e1){…}
catch (IOException e2) {…}
Catching Exceptions
Catchers can also re-throw an exception or throw
exception that is different from the exception caught.
graphics g = image.getGraphics();
try { …}
catch (MalformedURLException e)
{ g.dispose();
throw e;
}
We wish to dispose the graphics object g, but we don’t know how
to deal with the exception.
How to create a new exception and throw it?
The finally clause
try
{ code
more code}
catch( ExceptionType e)
{ handler for this exception }
finally
{ .. }
The finally block is executed regardless
whether exceptions are thrown in the try block.
Useful in situations where resources must be
released no matter what happened
• A caution about the finally clause:
– Codes in the finally block are executed even
there are return statements in the try block
public static int f(int n)
{ try
{ return n* n;
}
finally
{ if ( n==2) return 0;
}
The finally clause
Dealing with Exceptions
Search for handler: Steps:
– Tries to find a handler in the Catch block for the
current exception in the current method. Considers a
match if the thrown object can legally be assigned to the
exception handler’s argument.
– If not found, move to the caller of this method
– If not there, go another level upward, and so on.
– If no handler found, program terminates.
C++ Notes
Java exception handling similar to that of C++,
except:
– C++ enforces the throw specifier at run time, while
Java checks throws specifier at compile time.
– In C++ a function can throw an exception in case of
no throw specification, while in Java a method
can only throw exceptions advertised.
– In C++ you can throw values of any type, while in
Java you can only throw objects of a subclass of
Throwable.

More Related Content

What's hot

What's hot (20)

Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
 
Exceptions handling notes in JAVA
Exceptions handling notes in JAVAExceptions handling notes in JAVA
Exceptions handling notes in JAVA
 
Java exception
Java exception Java exception
Java exception
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception
ExceptionException
Exception
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Built in exceptions
Built in exceptions Built in exceptions
Built in exceptions
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handler
Exception handler Exception handler
Exception handler
 
Exception handling
Exception handlingException handling
Exception handling
 
Nalinee java
Nalinee javaNalinee java
Nalinee java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception hierarchy
Exception hierarchyException hierarchy
Exception hierarchy
 

Viewers also liked

Handling Exceptions In C & C++[Part A]
Handling Exceptions In C & C++[Part A]Handling Exceptions In C & C++[Part A]
Handling Exceptions In C & C++[Part A]ppd1961
 
Financial crimes report to the public
Financial crimes report to the publicFinancial crimes report to the public
Financial crimes report to the publicPollard Seifert
 
Cara cepat hamil menurut islam
Cara cepat hamil menurut islamCara cepat hamil menurut islam
Cara cepat hamil menurut islamMuadz Akbar
 
foursquare - Group C
foursquare - Group Cfoursquare - Group C
foursquare - Group CAna Elisa Gil
 
King's College Hospital- Complimentary feedback
King's College Hospital- Complimentary feedbackKing's College Hospital- Complimentary feedback
King's College Hospital- Complimentary feedbackEmil Toshev
 
Proceso europero el colonialismo
Proceso europero el colonialismoProceso europero el colonialismo
Proceso europero el colonialismoMiguel Orozco
 
Examen practica b sistemas de ing para comercial
Examen practica b sistemas de ing para comercialExamen practica b sistemas de ing para comercial
Examen practica b sistemas de ing para comercialivonne1622
 
Estrategia de aprendizaje no. 1
Estrategia de aprendizaje no. 1Estrategia de aprendizaje no. 1
Estrategia de aprendizaje no. 1Clara Ruiz Fester
 
JAVA Collections frame work ppt
 JAVA Collections frame work ppt JAVA Collections frame work ppt
JAVA Collections frame work pptRanjith Alappadan
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handlingsanya6900
 
9781285852744 ppt ch14
9781285852744 ppt ch149781285852744 ppt ch14
9781285852744 ppt ch14Terry Yoast
 
Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++Deepak Tathe
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handlingAlpesh Oza
 

Viewers also liked (20)

Exception handling
Exception handlingException handling
Exception handling
 
12 exception handling
12 exception handling12 exception handling
12 exception handling
 
Handling Exceptions In C & C++[Part A]
Handling Exceptions In C & C++[Part A]Handling Exceptions In C & C++[Part A]
Handling Exceptions In C & C++[Part A]
 
Financial crimes report to the public
Financial crimes report to the publicFinancial crimes report to the public
Financial crimes report to the public
 
Cara cepat hamil menurut islam
Cara cepat hamil menurut islamCara cepat hamil menurut islam
Cara cepat hamil menurut islam
 
foursquare - Group C
foursquare - Group Cfoursquare - Group C
foursquare - Group C
 
Fellas Booklet 2016
Fellas Booklet 2016Fellas Booklet 2016
Fellas Booklet 2016
 
King's College Hospital- Complimentary feedback
King's College Hospital- Complimentary feedbackKing's College Hospital- Complimentary feedback
King's College Hospital- Complimentary feedback
 
Proceso europero el colonialismo
Proceso europero el colonialismoProceso europero el colonialismo
Proceso europero el colonialismo
 
Health and safety intructions
Health and safety intructionsHealth and safety intructions
Health and safety intructions
 
Examen practica b sistemas de ing para comercial
Examen practica b sistemas de ing para comercialExamen practica b sistemas de ing para comercial
Examen practica b sistemas de ing para comercial
 
Estrategia de aprendizaje no. 1
Estrategia de aprendizaje no. 1Estrategia de aprendizaje no. 1
Estrategia de aprendizaje no. 1
 
Cembre 2A60 Crimp Lugs 300sqmm 11-33kV
Cembre 2A60 Crimp Lugs 300sqmm 11-33kVCembre 2A60 Crimp Lugs 300sqmm 11-33kV
Cembre 2A60 Crimp Lugs 300sqmm 11-33kV
 
JAVA Collections frame work ppt
 JAVA Collections frame work ppt JAVA Collections frame work ppt
JAVA Collections frame work ppt
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
 
TDR resume 02-20-15
TDR resume 02-20-15TDR resume 02-20-15
TDR resume 02-20-15
 
9781285852744 ppt ch14
9781285852744 ppt ch149781285852744 ppt ch14
9781285852744 ppt ch14
 
java applets
java appletsjava applets
java applets
 
Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 

Similar to 06 exceptions

Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allHayomeTakele
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptxRDeepa9
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptxRDeepa9
 
exception-handling-in-java.ppt
exception-handling-in-java.pptexception-handling-in-java.ppt
exception-handling-in-java.pptJAYESHRODGE
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling pptJavabynataraJ
 
exceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.pptexceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.pptyjrtytyuu
 
exception-handling-in-java.ppt unit 2
exception-handling-in-java.ppt unit 2exception-handling-in-java.ppt unit 2
exception-handling-in-java.ppt unit 2thenmozhip8
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in javajunnubabu
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingAboMohammad10
 
Exception handling
Exception handlingException handling
Exception handlingMinal Maniar
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaARAFAT ISLAM
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-ivRubaNagarajan
 

Similar to 06 exceptions (20)

Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
exception-handling-in-java.ppt
exception-handling-in-java.pptexception-handling-in-java.ppt
exception-handling-in-java.ppt
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
exceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.pptexceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.ppt
 
exception-handling-in-java.ppt unit 2
exception-handling-in-java.ppt unit 2exception-handling-in-java.ppt unit 2
exception-handling-in-java.ppt unit 2
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Exception Handling.ppt
 Exception Handling.ppt Exception Handling.ppt
Exception Handling.ppt
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
Satish training ppt
Satish training pptSatish training ppt
Satish training ppt
 

More from Waheed Warraich (11)

java jdbc connection
java jdbc connectionjava jdbc connection
java jdbc connection
 
java networking
 java networking java networking
java networking
 
java threads
java threadsjava threads
java threads
 
java swing
java swingjava swing
java swing
 
09events
09events09events
09events
 
08graphics
08graphics08graphics
08graphics
 
05io
05io05io
05io
 
04inherit
04inherit04inherit
04inherit
 
03class
03class03class
03class
 
02basics
02basics02basics
02basics
 
01intro
01intro01intro
01intro
 

Recently uploaded

Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 

Recently uploaded (20)

Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 

06 exceptions

  • 1. Topic 6: Exceptions Reading: Chapter 11 Advanced Programming Techniques
  • 2. Objective/Outline • Objective: Study how to handle exceptions in java • Outline: – Introduction – Java exception classes (Checked vs unchecked exceptions) – Dealing with exceptions • Throwing exceptions • Catching exceptions
  • 3. Introduction Causes of errors User input errors: typos, malformed URL, wrong file name, wrong info in file… Hardware errors: Disk full, printer out of paper or down, web page unavailable… Code errors: invalid array index, bad cast, read past end of file, pop empty stack, null object reference…
  • 4. Introduction Goals of error handling Don’t want: Want: Return to a safe state and enable user to execute other commands Allow user to save work and terminate program gracefully.
  • 5. Introduction • Java exception handling mechanism: Every method is allowed to have two exit paths – No errors occur • Method exits in the normal way • Returns a value • Control passed to the calling code. – If errors occur • Method exits via an alternative exit path • Throws an object that encapsulates the error information • Control passed to exception mechanism that searches for an appropriate exception handler to deal with the error condition
  • 6. Outline Introduction Java exception classes Dealing with exceptions  Throwing exceptions  Catching exceptions
  • 7. Java Exception Classes JVM internal errors Java has many classes for error handling. They are called exception classes
  • 9. Unchecked exceptions Error: For internal errors in JVM. RuntimeException: Logical errors in program (C++ logical-error).  Bad cast  Out-of-bound array access  Null reference access Those two exceptions are unchecked  JVM internal errors beyond your control  You should not allow logical errors at the first place
  • 10. • All other exceptions (C++ runtime_error) are checked, i.e. you have to explicitly handle them. Otherwise compiler errors results in. – Trying to read pass end of file – Open a malformed URL – … AclNotFoundException, ActivationException, AWTException, BadLocationException, ClassNotFoundException, CloneNotSupportedException, DataFormatException, ExpandVetoException, GeneralSecurityException, IllegalAccessException, InstantiationException, InterruptedException, IntrospectionException, InvocationTargetException, Checked exceptions Can be found in online API
  • 11. Exceptions • Typically, what methods does an exception class have? – Check IOException
  • 12. Java Exception Classes You can define new Exception classes. class FileFormatException extends IOException { // default constructor public FileFormatException() {} //constructor contains a detailed message public FileFormatException(String message) { super( message ); } New Exception class must be subclass of Throwable Most programs throw and catch objects that derive from the Exception class
  • 13. Outline Introduction Java exception classes Dealing with exceptions  Throwing exceptions  Catching exceptions
  • 14. Dealing with Exceptions • Need to consider exceptions when writing each method – Identifying possible exceptions • Check each line of code inside the method – If a method from someone else is called, check API to see if it throws exceptions – If some other method you wrote is called, also check to see if it throws exceptions. – Dealing with exceptions • If checked exceptions might be thrown at any point inside the method, you need to deal with it – Catching exceptions: Handle an exception in the current method.
  • 15. Throwing Exceptions • Throw an exception generated by method call: public void readData(BufferedReader in)throws IOException { String s = in.readLine(); StringTokenizer t = new StringTokenizer(s, "|"); name = t.nextToken(); salary = Double.parseDouble(t.nextToken()); int y = Integer.parseInt(t.nextToken()); int m = Integer.parseInt(t.nextToken()); int d = Integer.parseInt(t.nextToken()); GregorianCalendar calendar = new GregorianCalendar(y, m - 1, d); // GregorianCalendar uses 0 = January hireDay = calendar.getTime(); }//DataFileTest.java from Topic 5
  • 16. Throwing Exceptions • The method readLine of BufferedReader throws an IOExpcetion, a checked exception – We do not deal with this exception in the current method. So we state that the readData method might throw IOException. • If you simply ignore it, compiler error results in. Try this.
  • 17. Throwing Exceptions • Notes: – Can throw multiple types of exceptions public void readData(BufferedReader in) throws IOException, EOFException – Overriding method in subclass cannot throw more exceptions than corresponding method in superclass • If method in superclass does not throw any exceptions, overriding method in subclass cannot either
  • 18. Outline Introduction Java exception classes Dealing with exceptions  Throwing exceptions  Catching exceptions
  • 19. Catching Exceptions Catch exceptions with try/catch block try { code more code } catch( ExceptionType e) { handler for this exception } If a statement in the try block throws an exception The remaining statements in the block are skipped Handler code inside catch block executed. If no exceptions are thrown by codes in the try block, the catch block is skipped.
  • 20. Dealing with Exceptions Example: try { average = total/count; System.out.println(“Average is ” + average); } catch (ArithmeticException e) { System.out.println(“Oops: ”+ e); average = -1;} If count is 0, this code will print out something like “Oops: division by zero”.
  • 21. Catching Exceptions public static void main(String[] args) { try { BufferedReader in = new BufferedReader( new FileReader(args[0])); Employee[] newStaff = readData(in); … } catch(IOException exception) { exception.printStackTrace(); }} //ExceptionTest.java This code will exit right away with an error message if something goes wrong in readData or in the constructor of FilerReader (an IOException will be thrown)
  • 22. Catching Multiple Exceptions Can have multiple catchers for multiple types of exceptions: public static void main(String[] args) { try { BufferedReader in = new BufferedReader( new FileReader(args[0])); Employee[] e = readData(in); … } catch(IOException e1) { exception.printStackTrace(); } catch(ArrayIndexOutOfBoundsException e2) { System.out.print("No file name provided " ); System.exit(1); } } // ExceptionTest2.java What if GeneralSecurityException occurs in the try block? Might throw ArrayIndexOutOfBoundsExpection
  • 23. Dealing with Exceptions Note that the following will produce a compiling error. Why? try {…} catch (Exception e3) {…} catch (ArithmeticException e1){…} catch (IOException e2) {…}
  • 24. Catching Exceptions Catchers can also re-throw an exception or throw exception that is different from the exception caught. graphics g = image.getGraphics(); try { …} catch (MalformedURLException e) { g.dispose(); throw e; } We wish to dispose the graphics object g, but we don’t know how to deal with the exception. How to create a new exception and throw it?
  • 25. The finally clause try { code more code} catch( ExceptionType e) { handler for this exception } finally { .. } The finally block is executed regardless whether exceptions are thrown in the try block. Useful in situations where resources must be released no matter what happened
  • 26. • A caution about the finally clause: – Codes in the finally block are executed even there are return statements in the try block public static int f(int n) { try { return n* n; } finally { if ( n==2) return 0; } The finally clause
  • 27. Dealing with Exceptions Search for handler: Steps: – Tries to find a handler in the Catch block for the current exception in the current method. Considers a match if the thrown object can legally be assigned to the exception handler’s argument. – If not found, move to the caller of this method – If not there, go another level upward, and so on. – If no handler found, program terminates.
  • 28. C++ Notes Java exception handling similar to that of C++, except: – C++ enforces the throw specifier at run time, while Java checks throws specifier at compile time. – In C++ a function can throw an exception in case of no throw specification, while in Java a method can only throw exceptions advertised. – In C++ you can throw values of any type, while in Java you can only throw objects of a subclass of Throwable.