SlideShare una empresa de Scribd logo
1 de 17
Finally	 LIS4930 © PIC There are times when you want some code to run regardless of an exception – you want it to run no matter what! The finally block is where you put code that must run regardless of an exception. A finally block lets you put all your important cleanup code in one place instead of duplicating it like this: try { turnOvenOn( ); x.bake( ); turnOvenOff( ); } catch(BakingException ex) { ex.printStackTrace(); turnOvenOff( ); } try { turnOvenOn( ); x.bake( ); } catch(BakingException ex) { ex.printStackTrace(); } finally { turnOvenOff( ); }
A Method Can Throw More Than One Exception LIS4930 © PIC public class Laundry { 	public void doLaundry( ) throws PantsException, ShoeException { 		// code that could throw either exception 	} } public class Foo { 	public void go( ) { 		Laundry laundry = new Laundry( ); 		try { laundry.doLaundry( ); 		} catch(PantsException ex) { 			// recovery code 		} catch(ShoeException ex) { 			// recovery code 		} 	} }
Exceptions Are Polymorphic LIS4930 © PIC Don’t forget Exceptions are objects so a ClothingException can be extended into ShirtExceptions, PantsExceptions, and DressExceptions. Therefore: 1 2 You can DECLARE exceptions using a supertype of the exceptions you throw. You can CATCH exceptions using a supertype of the exception thrown. Just because you CAN catch everything with one big super polymorphic catch, doesn’t mean you SHOULD. Write a different catch block for each exception that you need to handle uniquely. Look at page 330 for an example of polymorphic exceptions
Catching Multiple Exceptions Multiple catch blocks must be ordered from smallest to biggest. You can’t put bigger baskets above smaller baskets. LIS4930 © PIC Don’t do this! try { laundry.doLaundry( ) } catch (ClothingExceptionce) { 	// recovery code goes here } catch (ShoeException se ) { 	// recovery code goes here } catch (DressException de) { 	// recovery code goes here }
Paying It Forward LIS4930 © PIC If you don’t want to handle an exception you can just throw it yourself so that whomever calls YOU will have to handle the exception.  If you call a risky method that does throw an exception, instead of you handling it, you can keep throwing it. public void foo( ) throws PantsException, ShoeException { 	// call risky method without a try/catch block laundry.doLaundry( ); }
Ducking (by paying it forward) Only Delays the Inevitable LIS4930 © PIC public class Washer { 	Laundry laundry = new Laundry( ); 	public void foo( ) throws ClothingException{ laundry.doLaundry( ); 	} 	public static void main(String[] args) throws ClothingException{ 		Washer a = new Washer( ); a.foo( ); 	} } 1 2 3 4 doLaundry( ) throws a ClothingException foo( ) ducks the exception main( ) ducks the exception The JVM shuts down
Handle or Declare! LIS4930 © PIC So now we’ve seen both ways to satisfy the compiler when you call a risky (exception-throwing) method. 1 2 HANDLE – Wrap the risky call in a try/catch block DECLARE – duck it / pay it forward Let’s look at the sequencer to see how each method works.
Exception Rules LIS4930 © PIC 1 2 3 4 You cannot have a catch or finally without a try You cannot put code between the try and the catch A try MUST be followed by either a catch or a finally A try with only a finally (no catch) must still declare the exception void go ( ) { Foof = new Foo( ); f.foof( ); catch(fooException ex) { } } try { x.doStuff( ); } finally { 	// cleanup } try { x.doStuff( ); }  inty = 43; } catch (Exception ex ) { } void go ( ) throws FooException { 	try { x.doStuff( ); 	} finally { } }
Familiar Example LIS4930 © PIC But, what about this? We now know what this means.
Input and Output The java.iopackage includes a rich collection of different classes to support I/O. Different classes provide different ways for programs to organize and retrieve data. Java programs do not communicate directly with external devices, instead they create a stream object to connect the program to the device. Each stream functions as a conduit that establishes a path for the data to flow between the program and the I/O device. LIS4930 © PIC
Streams Java supports several different streams for different purposes. LIS4930 © PIC Output Stream Executing Program File (on disk) Input Stream Executing Program File (on disk)
Stream Hierarchy LIS4930 © PIC Output Stream (abstract) Input Stream (abstract) FileOutputStream FileInputStream to write raw bytes to read raw bytes ObjectOutputStream ObjectInputStream to write whole objects to read whole objects FilterOutputStream FilterInputStream DataOutputStream DataInputStream to write primitive values  to read primitive values
Using Streams Open the file for input, instantiating associated stream objects. Call read methods to retrieve part of or the entire stream’s content. Close the file/stream. LIS4930 © PIC Input Streams Output Streams Open the file for output, instantiating associated stream objects. Call read methods to write data into the stream. Close the file/stream.
DataInputStreams & DataOutputStreams LIS4930 © PIC FileOutputStream FileInputStream DataOutputStream DataInputStream Executing Program Executing Program File (on disk) File (on disk)
Text Files LIS4930 © PIC Input Stream Input Stream Output Stream Output Stream BufferedReader Writer Reader Executing Program Executing Program Executing Program Executing Program Reader Writer File (on disk) File (on disk) File (on disk) File (on disk) BufferedWriter
Familiar Example LIS4930 © PIC Now we know what this means What if we didn’t “duck” the exceptions?
Input and Output of Files LIS4930 © PIC Input Stream Input Stream Output Stream Use a FileReader/FileWriter objects as your “Reader” conduit. BufferedReader FileReader Executing Program Executing Program Executing Program FileReader FileWriter File (on disk) File (on disk) File (on disk) BufferedWriter

Más contenido relacionado

Similar a 14b exceptions

JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJAYAPRIYAR7
 
forwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docxforwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docxbudbarber38650
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
 
Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9Ismar Silveira
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsAzul Systems, Inc.
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpen Gurukul
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
Exception Handling
Exception HandlingException Handling
Exception HandlingSunil OS
 
Groovy Powered Clean Code
Groovy Powered Clean CodeGroovy Powered Clean Code
Groovy Powered Clean CodeGR8Conf
 
Exception Handling
Exception HandlingException Handling
Exception Handlingbackdoor
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templatesfarhan amjad
 

Similar a 14b exceptions (20)

02 prepcode
02 prepcode02 prepcode
02 prepcode
 
12 constructors
12 constructors12 constructors
12 constructors
 
Thread
ThreadThread
Thread
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
 
forwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docxforwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docx
 
Java doc Pr ITM2
Java doc Pr ITM2Java doc Pr ITM2
Java doc Pr ITM2
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9
 
E:\Plp 2009 2\Plp 9
E:\Plp 2009 2\Plp 9E:\Plp 2009 2\Plp 9
E:\Plp 2009 2\Plp 9
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Groovy Powered Clean Code
Groovy Powered Clean CodeGroovy Powered Clean Code
Groovy Powered Clean Code
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
 
Twins: OOP and FP
Twins: OOP and FPTwins: OOP and FP
Twins: OOP and FP
 
C++ programming
C++ programmingC++ programming
C++ programming
 
C++ programming
C++ programmingC++ programming
C++ programming
 
Android code convention
Android code conventionAndroid code convention
Android code convention
 

Más de Program in Interdisciplinary Computing (20)

Phpmysqlcoding
PhpmysqlcodingPhpmysqlcoding
Phpmysqlcoding
 
Database basics
Database basicsDatabase basics
Database basics
 
CGS2835 HTML5
CGS2835 HTML5CGS2835 HTML5
CGS2835 HTML5
 
Mysocial databasequeries
Mysocial databasequeriesMysocial databasequeries
Mysocial databasequeries
 
Mysocial databasequeries
Mysocial databasequeriesMysocial databasequeries
Mysocial databasequeries
 
CGS2835 HTML5
CGS2835 HTML5CGS2835 HTML5
CGS2835 HTML5
 
01 intro tousingjava
01 intro tousingjava01 intro tousingjava
01 intro tousingjava
 
Web architecture v3
Web architecture v3Web architecture v3
Web architecture v3
 
Xhtml
XhtmlXhtml
Xhtml
 
Webdev
WebdevWebdev
Webdev
 
Web architecture
Web architectureWeb architecture
Web architecture
 
Sdlc
SdlcSdlc
Sdlc
 
Mysocial
MysocialMysocial
Mysocial
 
Javascript
JavascriptJavascript
Javascript
 
Javascript
JavascriptJavascript
Javascript
 
Html5
Html5Html5
Html5
 
Frameworks
FrameworksFrameworks
Frameworks
 
Drupal
DrupalDrupal
Drupal
 
Database
DatabaseDatabase
Database
 
Javascript2
Javascript2Javascript2
Javascript2
 

14b exceptions

  • 1. Finally LIS4930 © PIC There are times when you want some code to run regardless of an exception – you want it to run no matter what! The finally block is where you put code that must run regardless of an exception. A finally block lets you put all your important cleanup code in one place instead of duplicating it like this: try { turnOvenOn( ); x.bake( ); turnOvenOff( ); } catch(BakingException ex) { ex.printStackTrace(); turnOvenOff( ); } try { turnOvenOn( ); x.bake( ); } catch(BakingException ex) { ex.printStackTrace(); } finally { turnOvenOff( ); }
  • 2. A Method Can Throw More Than One Exception LIS4930 © PIC public class Laundry { public void doLaundry( ) throws PantsException, ShoeException { // code that could throw either exception } } public class Foo { public void go( ) { Laundry laundry = new Laundry( ); try { laundry.doLaundry( ); } catch(PantsException ex) { // recovery code } catch(ShoeException ex) { // recovery code } } }
  • 3. Exceptions Are Polymorphic LIS4930 © PIC Don’t forget Exceptions are objects so a ClothingException can be extended into ShirtExceptions, PantsExceptions, and DressExceptions. Therefore: 1 2 You can DECLARE exceptions using a supertype of the exceptions you throw. You can CATCH exceptions using a supertype of the exception thrown. Just because you CAN catch everything with one big super polymorphic catch, doesn’t mean you SHOULD. Write a different catch block for each exception that you need to handle uniquely. Look at page 330 for an example of polymorphic exceptions
  • 4. Catching Multiple Exceptions Multiple catch blocks must be ordered from smallest to biggest. You can’t put bigger baskets above smaller baskets. LIS4930 © PIC Don’t do this! try { laundry.doLaundry( ) } catch (ClothingExceptionce) { // recovery code goes here } catch (ShoeException se ) { // recovery code goes here } catch (DressException de) { // recovery code goes here }
  • 5. Paying It Forward LIS4930 © PIC If you don’t want to handle an exception you can just throw it yourself so that whomever calls YOU will have to handle the exception. If you call a risky method that does throw an exception, instead of you handling it, you can keep throwing it. public void foo( ) throws PantsException, ShoeException { // call risky method without a try/catch block laundry.doLaundry( ); }
  • 6. Ducking (by paying it forward) Only Delays the Inevitable LIS4930 © PIC public class Washer { Laundry laundry = new Laundry( ); public void foo( ) throws ClothingException{ laundry.doLaundry( ); } public static void main(String[] args) throws ClothingException{ Washer a = new Washer( ); a.foo( ); } } 1 2 3 4 doLaundry( ) throws a ClothingException foo( ) ducks the exception main( ) ducks the exception The JVM shuts down
  • 7. Handle or Declare! LIS4930 © PIC So now we’ve seen both ways to satisfy the compiler when you call a risky (exception-throwing) method. 1 2 HANDLE – Wrap the risky call in a try/catch block DECLARE – duck it / pay it forward Let’s look at the sequencer to see how each method works.
  • 8. Exception Rules LIS4930 © PIC 1 2 3 4 You cannot have a catch or finally without a try You cannot put code between the try and the catch A try MUST be followed by either a catch or a finally A try with only a finally (no catch) must still declare the exception void go ( ) { Foof = new Foo( ); f.foof( ); catch(fooException ex) { } } try { x.doStuff( ); } finally { // cleanup } try { x.doStuff( ); } inty = 43; } catch (Exception ex ) { } void go ( ) throws FooException { try { x.doStuff( ); } finally { } }
  • 9. Familiar Example LIS4930 © PIC But, what about this? We now know what this means.
  • 10. Input and Output The java.iopackage includes a rich collection of different classes to support I/O. Different classes provide different ways for programs to organize and retrieve data. Java programs do not communicate directly with external devices, instead they create a stream object to connect the program to the device. Each stream functions as a conduit that establishes a path for the data to flow between the program and the I/O device. LIS4930 © PIC
  • 11. Streams Java supports several different streams for different purposes. LIS4930 © PIC Output Stream Executing Program File (on disk) Input Stream Executing Program File (on disk)
  • 12. Stream Hierarchy LIS4930 © PIC Output Stream (abstract) Input Stream (abstract) FileOutputStream FileInputStream to write raw bytes to read raw bytes ObjectOutputStream ObjectInputStream to write whole objects to read whole objects FilterOutputStream FilterInputStream DataOutputStream DataInputStream to write primitive values to read primitive values
  • 13. Using Streams Open the file for input, instantiating associated stream objects. Call read methods to retrieve part of or the entire stream’s content. Close the file/stream. LIS4930 © PIC Input Streams Output Streams Open the file for output, instantiating associated stream objects. Call read methods to write data into the stream. Close the file/stream.
  • 14. DataInputStreams & DataOutputStreams LIS4930 © PIC FileOutputStream FileInputStream DataOutputStream DataInputStream Executing Program Executing Program File (on disk) File (on disk)
  • 15. Text Files LIS4930 © PIC Input Stream Input Stream Output Stream Output Stream BufferedReader Writer Reader Executing Program Executing Program Executing Program Executing Program Reader Writer File (on disk) File (on disk) File (on disk) File (on disk) BufferedWriter
  • 16. Familiar Example LIS4930 © PIC Now we know what this means What if we didn’t “duck” the exceptions?
  • 17. Input and Output of Files LIS4930 © PIC Input Stream Input Stream Output Stream Use a FileReader/FileWriter objects as your “Reader” conduit. BufferedReader FileReader Executing Program Executing Program Executing Program FileReader FileWriter File (on disk) File (on disk) File (on disk) BufferedWriter