SlideShare a Scribd company logo
1 of 17
Exceptions in Java
What is an exception?
 An exception is an error condition that changes the
normal flow of control in a program
 Exceptions in Java separates error handling from main
business logic
 Based on ideas developed in Ada, Eiffel and C++
 Java has a uniform approach for handling all
synchronous errors
• From very unusual (e.g. out of memory)
• To more common ones your program should check itself (e.g.
index out of bounds)
• From Java run-time system errors (e.g., divide by zero)
• To errors that programmers detect and raise deliberately
Throwing and catching
 An error can throw an exception
throw <exception object>;
 By default, exceptions result in the thread
terminating after printing an error message
 However, exception handlers can catch specified
exceptions and recover from error
catch (<exception type> e) {
//statements that handle the exception
}
Throwing an exception
 Example creates a subclass of Exception and throws an exception:
class MyException extends Exception { }
class MyClass {
void oops()
{ if (/* no error occurred */)
{ /* normal processing */ }
else { /* error occurred */
throw new MyException();
}
} //oops
}//class MyClass
Exceptional flow of control
 Exceptions break the normal flow of control.
 When an exception occurs, the statement that
would normally execute next is not executed.
 What happens instead depends on:
– whether the exception is caught,
– where it is caught,
– what statements are executed in the ‘catch block’,
– and whether you have a ‘finally block’.
Approaches to handling an exception
1. Prevent the exception from happening
2. Catch it in the method in which it occurs, and either
a. Fix up the problem and resume normal execution
b. Rethrow it
c. Throw a different exception
3. Declare that the method throws the exception
4. With 1. and 2.a. the caller never knows there was an
error.
5. With 2.b., 2.c., and 3., if the caller does not handle the
exception, the program will terminate and display a
stack trace
Exception hierarchy
 Java organizes exceptions in inheritance tree:
– Throwable
– Error
– Exception
 RuntimeException
 TooManyListenersException
 IOException
 AWTException
Java is strict
 Unlike C++, is quite strict about catching exceptions
 If it is a checked exception
– (all except Error, RuntimeException and their subclasses),
– Java compiler forces the caller must either catch it
– or explicitly re-throw it with an exception specification.
 Why is this a good idea?
 By enforcing exception specifications from top to bottom,
Java guarantees exception correctness at compile time.
 Here’s a method that ducks out of catching an exception by
explicitly re-throwing it:
void f() throws tooBig, tooSmall, divZero {
– The caller of this method now must either catch these
exceptions or rethrow them in its specification.
Error and RuntimeException
 Error
– “unchecked”, thus need not be in ‘throws’ clause
– Serious system problems (e.g. ThreadDeath, OutOfMemoryError)
– It’s very unlikely that the program will be able to recover, so
generally you should NOT catch these.
 RuntimeException
– “unchecked”, thus need not be in ‘throws’ clause
– Also can occur almost anywhere, e.g. ArithmeticException,
NullPointerException, IndexOutOfBoundsException
– Try to prevent them from happening in the first place!
 System will print stop program and print a trace
Catching an exception
try { // statement that could throw an exception
}
catch (<exception type> e) {
// statements that handle the exception
}
catch (<exception type> e) { //e higher in hierarchy
// statements that handle the exception
}
finally {
// release resources
}
//other statements
 At most one catch block executes
 finally block always executes once, whether there’s an error or
not
Execution of try catch blocks
 For normal execution:
– try block executes, then finally block executes, then other statements execute
 When an error is caught and the catch block throws an exception or returns:
– try block is interrupted
– catch block executes (until throw or return statement)
– finally block executes
 When error is caught and catch block doesn’t throw an exception or return:
– try block is interrupted
– catch block executes
– finally block executes
– other statements execute
 When an error occurs that is not caught:
– try block is interrupted
– finally block executes
Example:
try { p.a = 10; }
catch (NullPointerException e)
{ System.out.println("p was null"); }
catch (Exception e)
{ System.out.println("other error occurred"); }
catch (Object obj)
{ System.out.println("Who threw that object?"); }
finally { System.out.println(“final processing"); }
System.out.println(“Continue with more statements");
Catch processing
 When an exception occurs, the nested try/catch statements are
searched for a catch parameter matching the exception class
 A parameter is said to match the exception if it:
– is the same class as the exception; or
– is a superclass of the exception; or
– if the parameter is an interface, the exception class implements the
interface.
 The first try/catch statement that has a parameter that matches
the exception has its catch statement executed.
 After the catch statement executes, execution resumes with the
finally statement, then the statements after the try/catch
statement.
Catch processing example
print("now");   
try   
{ print("is ");      
  throw new MyException();     
  print("a ");   
} 
catch(MyException e)   { print("the ");   }   
print("timen"); 
 Prints "now is the time".
 Note that exceptions don't have to be used only for error handling
 Would it be a good idea to exceptions for non-error processing?
 But any other use is likely to result in code that's hard to understand.
Declaring an exception type
 Inherit from an existing exception type.
 Provide a default constructor
 and a constructor with one arg, type String.
 Both should call super(astring);
 Example:
class MyThrowable extends Throwable { 
// checked exception
  MyThrowable () {
     super ("Generated MyThrowable");
  }
  MyThrowable (String s) { super (s); }
}
Declaring an exception type
 Inherit from an existing exception type.
 Provide a default constructor
 and a constructor with one arg, type String.
 Both should call super(astring);
class ErrorThrower {
public void errorMethod() throws MyThrowable
{ throw new MyThrowable ("ErrorThrower");
// forces this method to declare MyThrowable
}
}
Exceptions are ubiquitous in Java
 Exception handling required for all read methods
– Also many other system methods
 If you use one of Java's built in class methods and
it throws an exception, you must catch it (i.e.,
surround it in a try/catch block) or rethrow it, or you
will get a compile time error:
char ch;
try { ch = (char) System.in.read(); }
catch (IOException e)
{ System.err.println(e); return;

More Related Content

What's hot

Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
Prabhdeep Singh
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Prasad Sawant
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
Deepak Sharma
 

What's hot (20)

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
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java Exception Handling and Applets
Java Exception Handling and AppletsJava Exception Handling and Applets
Java Exception Handling and Applets
 
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
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Exception handling in JAVA
Exception handling in JAVAException handling in JAVA
Exception handling in JAVA
 
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 javaException handling in java
Exception handling in java
 
Exception
ExceptionException
Exception
 
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
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 

Viewers also liked

Y tú que haces estudias o aprehendes
Y tú que haces estudias o aprehendesY tú que haces estudias o aprehendes
Y tú que haces estudias o aprehendes
enfermeriamisahuamam
 
Presentations tips
Presentations tipsPresentations tips
Presentations tips
rioulrich
 

Viewers also liked (20)

Media institutions
Media institutions Media institutions
Media institutions
 
Inventory Valuation
Inventory ValuationInventory Valuation
Inventory Valuation
 
Introduction to REST
Introduction to RESTIntroduction to REST
Introduction to REST
 
Swisscom: Smart Homes & Security Risks
Swisscom: Smart Homes & Security RisksSwisscom: Smart Homes & Security Risks
Swisscom: Smart Homes & Security Risks
 
Y tú que haces estudias o aprehendes
Y tú que haces estudias o aprehendesY tú que haces estudias o aprehendes
Y tú que haces estudias o aprehendes
 
Sistemas operativos emilio
Sistemas operativos emilioSistemas operativos emilio
Sistemas operativos emilio
 
Presentations tips
Presentations tipsPresentations tips
Presentations tips
 
Medio ambiente
Medio ambienteMedio ambiente
Medio ambiente
 
Sci fi film plan
Sci fi film planSci fi film plan
Sci fi film plan
 
Anish Mondal
Anish MondalAnish Mondal
Anish Mondal
 
Latihan pdf word
Latihan pdf wordLatihan pdf word
Latihan pdf word
 
Dergi tasarim dunyasi
Dergi  tasarim dunyasiDergi  tasarim dunyasi
Dergi tasarim dunyasi
 
Internet der Ingenieure - reale und virtuelle Welten verschmelzen - AWS IoT W...
Internet der Ingenieure - reale und virtuelle Welten verschmelzen - AWS IoT W...Internet der Ingenieure - reale und virtuelle Welten verschmelzen - AWS IoT W...
Internet der Ingenieure - reale und virtuelle Welten verschmelzen - AWS IoT W...
 
' Rational Numbers ' - The Maths Quiz with a crappy title :-D
' Rational Numbers ' - The Maths Quiz with a crappy title :-D' Rational Numbers ' - The Maths Quiz with a crappy title :-D
' Rational Numbers ' - The Maths Quiz with a crappy title :-D
 
An Introduction to Voice and SMS in LTE Networks
An Introduction to Voice and SMS in LTE NetworksAn Introduction to Voice and SMS in LTE Networks
An Introduction to Voice and SMS in LTE Networks
 
tema 1 los seres vivos 2 eso
 tema 1 los seres vivos 2 eso tema 1 los seres vivos 2 eso
tema 1 los seres vivos 2 eso
 
Webshop Analyse
Webshop Analyse Webshop Analyse
Webshop Analyse
 
Arbeiterbewegung Natur Technik
Arbeiterbewegung Natur TechnikArbeiterbewegung Natur Technik
Arbeiterbewegung Natur Technik
 
Open Data als Chance für die IT-Branche
Open Data als Chance für die IT-BrancheOpen Data als Chance für die IT-Branche
Open Data als Chance für die IT-Branche
 
Notbeleuchtung Normenänderungen 2015
Notbeleuchtung Normenänderungen 2015Notbeleuchtung Normenänderungen 2015
Notbeleuchtung Normenänderungen 2015
 

Similar to Exceptions in java

Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
Rakesh Madugula
 
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
HayomeTakele
 

Similar to Exceptions in java (20)

Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
 
JAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdfJAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdf
 
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
 
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 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.ppt
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handling
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
 

More from Manav Prasad (20)

Experience with mulesoft
Experience with mulesoftExperience with mulesoft
Experience with mulesoft
 
Mulesoftconnectors
MulesoftconnectorsMulesoftconnectors
Mulesoftconnectors
 
Mule and web services
Mule and web servicesMule and web services
Mule and web services
 
Mulesoft cloudhub
Mulesoft cloudhubMulesoft cloudhub
Mulesoft cloudhub
 
Perl tutorial
Perl tutorialPerl tutorial
Perl tutorial
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Jpa
JpaJpa
Jpa
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
Json
Json Json
Json
 
The spring framework
The spring frameworkThe spring framework
The spring framework
 
Rest introduction
Rest introductionRest introduction
Rest introduction
 
Junit
JunitJunit
Junit
 
Xml parsers
Xml parsersXml parsers
Xml parsers
 
Xpath
XpathXpath
Xpath
 
Xslt
XsltXslt
Xslt
 
Xhtml
XhtmlXhtml
Xhtml
 
Css
CssCss
Css
 
Introduction to html5
Introduction to html5Introduction to html5
Introduction to html5
 
Ajax
AjaxAjax
Ajax
 
J query
J queryJ query
J query
 

Recently uploaded

Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
UXDXConf
 

Recently uploaded (20)

Connecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAKConnecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAK
 
AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101
 
Strategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering TeamsStrategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering Teams
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
 
THE BEST IPTV in GERMANY for 2024: IPTVreel
THE BEST IPTV in  GERMANY for 2024: IPTVreelTHE BEST IPTV in  GERMANY for 2024: IPTVreel
THE BEST IPTV in GERMANY for 2024: IPTVreel
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
Oauth 2.0 Introduction and Flows with MuleSoft
Oauth 2.0 Introduction and Flows with MuleSoftOauth 2.0 Introduction and Flows with MuleSoft
Oauth 2.0 Introduction and Flows with MuleSoft
 
Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdf
 
Designing for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at ComcastDesigning for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at Comcast
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 

Exceptions in java

  • 2. What is an exception?  An exception is an error condition that changes the normal flow of control in a program  Exceptions in Java separates error handling from main business logic  Based on ideas developed in Ada, Eiffel and C++  Java has a uniform approach for handling all synchronous errors • From very unusual (e.g. out of memory) • To more common ones your program should check itself (e.g. index out of bounds) • From Java run-time system errors (e.g., divide by zero) • To errors that programmers detect and raise deliberately
  • 3. Throwing and catching  An error can throw an exception throw <exception object>;  By default, exceptions result in the thread terminating after printing an error message  However, exception handlers can catch specified exceptions and recover from error catch (<exception type> e) { //statements that handle the exception }
  • 4. Throwing an exception  Example creates a subclass of Exception and throws an exception: class MyException extends Exception { } class MyClass { void oops() { if (/* no error occurred */) { /* normal processing */ } else { /* error occurred */ throw new MyException(); } } //oops }//class MyClass
  • 5. Exceptional flow of control  Exceptions break the normal flow of control.  When an exception occurs, the statement that would normally execute next is not executed.  What happens instead depends on: – whether the exception is caught, – where it is caught, – what statements are executed in the ‘catch block’, – and whether you have a ‘finally block’.
  • 6. Approaches to handling an exception 1. Prevent the exception from happening 2. Catch it in the method in which it occurs, and either a. Fix up the problem and resume normal execution b. Rethrow it c. Throw a different exception 3. Declare that the method throws the exception 4. With 1. and 2.a. the caller never knows there was an error. 5. With 2.b., 2.c., and 3., if the caller does not handle the exception, the program will terminate and display a stack trace
  • 7. Exception hierarchy  Java organizes exceptions in inheritance tree: – Throwable – Error – Exception  RuntimeException  TooManyListenersException  IOException  AWTException
  • 8. Java is strict  Unlike C++, is quite strict about catching exceptions  If it is a checked exception – (all except Error, RuntimeException and their subclasses), – Java compiler forces the caller must either catch it – or explicitly re-throw it with an exception specification.  Why is this a good idea?  By enforcing exception specifications from top to bottom, Java guarantees exception correctness at compile time.  Here’s a method that ducks out of catching an exception by explicitly re-throwing it: void f() throws tooBig, tooSmall, divZero { – The caller of this method now must either catch these exceptions or rethrow them in its specification.
  • 9. Error and RuntimeException  Error – “unchecked”, thus need not be in ‘throws’ clause – Serious system problems (e.g. ThreadDeath, OutOfMemoryError) – It’s very unlikely that the program will be able to recover, so generally you should NOT catch these.  RuntimeException – “unchecked”, thus need not be in ‘throws’ clause – Also can occur almost anywhere, e.g. ArithmeticException, NullPointerException, IndexOutOfBoundsException – Try to prevent them from happening in the first place!  System will print stop program and print a trace
  • 10. Catching an exception try { // statement that could throw an exception } catch (<exception type> e) { // statements that handle the exception } catch (<exception type> e) { //e higher in hierarchy // statements that handle the exception } finally { // release resources } //other statements  At most one catch block executes  finally block always executes once, whether there’s an error or not
  • 11. Execution of try catch blocks  For normal execution: – try block executes, then finally block executes, then other statements execute  When an error is caught and the catch block throws an exception or returns: – try block is interrupted – catch block executes (until throw or return statement) – finally block executes  When error is caught and catch block doesn’t throw an exception or return: – try block is interrupted – catch block executes – finally block executes – other statements execute  When an error occurs that is not caught: – try block is interrupted – finally block executes
  • 12. Example: try { p.a = 10; } catch (NullPointerException e) { System.out.println("p was null"); } catch (Exception e) { System.out.println("other error occurred"); } catch (Object obj) { System.out.println("Who threw that object?"); } finally { System.out.println(“final processing"); } System.out.println(“Continue with more statements");
  • 13. Catch processing  When an exception occurs, the nested try/catch statements are searched for a catch parameter matching the exception class  A parameter is said to match the exception if it: – is the same class as the exception; or – is a superclass of the exception; or – if the parameter is an interface, the exception class implements the interface.  The first try/catch statement that has a parameter that matches the exception has its catch statement executed.  After the catch statement executes, execution resumes with the finally statement, then the statements after the try/catch statement.
  • 14. Catch processing example print("now");    try    { print("is ");         throw new MyException();        print("a ");    }  catch(MyException e)   { print("the ");   }    print("timen");   Prints "now is the time".  Note that exceptions don't have to be used only for error handling  Would it be a good idea to exceptions for non-error processing?  But any other use is likely to result in code that's hard to understand.
  • 15. Declaring an exception type  Inherit from an existing exception type.  Provide a default constructor  and a constructor with one arg, type String.  Both should call super(astring);  Example: class MyThrowable extends Throwable {  // checked exception   MyThrowable () {      super ("Generated MyThrowable");   }   MyThrowable (String s) { super (s); } }
  • 16. Declaring an exception type  Inherit from an existing exception type.  Provide a default constructor  and a constructor with one arg, type String.  Both should call super(astring); class ErrorThrower { public void errorMethod() throws MyThrowable { throw new MyThrowable ("ErrorThrower"); // forces this method to declare MyThrowable } }
  • 17. Exceptions are ubiquitous in Java  Exception handling required for all read methods – Also many other system methods  If you use one of Java's built in class methods and it throws an exception, you must catch it (i.e., surround it in a try/catch block) or rethrow it, or you will get a compile time error: char ch; try { ch = (char) System.in.read(); } catch (IOException e) { System.err.println(e); return;