Coming up Exceptions An Example The Throws keyword Try and Catch

Slides:



Advertisements
Similar presentations
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Advertisements

Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CS102--Object Oriented Programming
HST 952 Computing for Biomedical Scientists Lecture 7.
COMP 121 Week 5: Exceptions and Exception Handling.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
COMP201 Java Programming Topic 6: Exceptions Reading: Chapter 11.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
COMP201 Java Programming Topic 7: Exceptions Reading: Chapter 11.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions CIS 304 Intermediate Java Programming for Business.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
Java Exception Handling
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
CS203 Java Object Oriented Programming Errors and Exception Handling.
COMP 103 Comparators and Comparable. RECAP  Iterator and Iterable TODAY  Comparator and Comparable  Exceptions 2 RECAP-TODAY.
Programming in C++ 1. Learning Outcome  At the end of this slide, student able to:  Understand what is Inheritance?  Compare between inheritance and.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Exception Handling Exceptions and language features to handle them.
Programming in C++ 1. Learning Outcome At the end of this slide, student able to:  Identify the different types of error in your program  Understand.
CS 2511 Fall  Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:  Examples: Out.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Peter Andreae Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington2012 Implementing.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Christina Aiello, 12/3/2015. Reminder: Seen in lecture notes for Exceptions: “Side note: we will NOT expect you to know/remember how to do keyboard input/output.
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.
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Introduction to Exceptions in Java CS201, SW Development Methods.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Eighth Lecture Exception Handling in Java
Exceptions In this lecture:
Chapter 10 – Exception Handling
MIT AITI 2003 Lecture14 Exceptions
Introduction Exception handling Exception Handles errors
Creating and Modifying Text part 2
CSE 501N Fall ’09 17: Exception Handling
Exceptions 10-Nov-18.
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Exception Handling Chapter 9.
Chapter 12 Exception Handling
OBJECT ORIENTED PROGRAMMING
Exception Handling Chapter 9 Edited by JJ.
Exception Handling.
Web Design & Development Lecture 7
Managing Errors and Exceptions
Intro to Exceptions (c) Eraj Basnayake
Java Exceptions Dan Fleck CS211.
CMSC 202 Exceptions 2nd Lecture.
Exceptions 25-Apr-19.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Exceptions 22-Apr-19.
Chapter 12 Exception Handling and Text IO Part 1
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Exceptions 10-May-19.
Java Basics Exception Handling.
Exceptions 5-Jul-19.
CMSC 202 Exceptions 2nd Lecture.
Exception Handling.
Presentation transcript:

Coming up Exceptions An Example The Throws keyword Try and Catch The flow Multiple exceptions Finally How exceptions are thrown What the complier checks Handle or Defer Recovery Writing your own

Exceptions – when it all goes wrong Lecture 17 and 18 Exceptions – when it all goes wrong

Coming up Exceptions An Example The Throws keyword Try and Catch The flow Multiple exceptions Finally How exceptions are thrown What the complier checks Handle or Defer Recovery Writing your own

ArrayIndexOutOfBoundsException You’ve probably come across those a fair amount But what is an exception What is this throwing business

Exceptions An Exception is an object The java tutorials say: The term exception is shorthand for the phrase "exceptional event." An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. Methods in Java use Exceptions to tell calling code “Something went wrong boss. I failed”

The exception object contains; When an error occurs in a method, the method creates an exception object and hands it off to the runtime system. The exception object contains; information about the error Error type state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception. http://java.sun.com/docs/books/tutorial/essential/exceptions

What could go wrong? Trying to open a file on the computer that isn’t there Trying to access more indexes than an array has Trying to cast incompatible types And many other situations....

Coming up Exceptions An Example The Throws keyword Try and Catch The flow Multiple exceptions Finally How exceptions are thrown What the complier checks Handle or Defer Recovery Writing your own

From Java tutorials (look them up!) readFile (){ open the file; determine its size; allocate that much memory; read the file into memory; close the file; } http://java.sun.com/docs/books/tutorial/essential/exceptions/advantages.html

But... What happens if the file can't be opened? What happens if the length of the file can't be determined? What happens if enough memory can't be allocated? What happens if the read fails? What happens if the file can't be closed? http://java.sun.com/docs/books/tutorial/essential/exceptions/advantages.html

Using if It sounds like we’re saying: If this goes wrong (or if this file isn’t there){ Do this recovery code } So why can’t I just use if statements? The Java tutorials have a good explanation

Error handling with if errorCodeType readFile { initialize errorCode = 0; open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } } else { errorCode = -2; errorCode = -3; close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode and -4; } errorCode = -5; return errorCode; http://java.sun.com/docs/books/tutorial/essential/exceptions/advantages.html

Error Handling with exceptions readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { } catch (memoryAllocationFailed) { } catch (readFailed) { } catch (fileCloseFailed) { } Pseudocode http://java.sun.com/docs/books/tutorial/essential/exceptions/advantages.html

Using exceptions means you can separate the error handling code from the functional code

Another pro for exceptions Using if statements normally means you will return a “special value” (if 0 is returned then everything went okay etc) A special return value can potentially (accidently?) be ignored

It is (almost) impossible for an exception to be ignored Failure to handle an exception will result in termination of the program Let’s look at a real usage – how do we find a risky method (one that is liable to throw an exception)?

Coming up Exceptions An Example The Throws keyword Try and Catch The flow Multiple exceptions Finally How exceptions are thrown What the complier checks Handle or Defer Recovery Writing your own

You can tell if a method will possibly throw an exception by the throws keyword

FileReader The FileReader object will read text files line by line and hand them to you as Strings It is constructed with a file name in the brackets If the constructor can’t find the file (the file must be in the same folder as the class file) it will throw an exception

Coming up Exceptions An Example The Throws keyword Try and Catch The flow Multiple exceptions Finally How exceptions are thrown What the complier checks Handle or Defer Recovery Writing your own

Try and catch We try something risky In java we use a try catch block And catch any problems that occur In java we use a try catch block

Try Catch Block So we wrap the code calling the constructor FileReader fr; fr = new FileReader(“myfile.txt”); In a try-catch block: try{ }catch(FileNotFoundException ex){ System.out.println(“Ooops!”); }

Exceptions An FileNotFoundException is an object That subclasses Exception The catch argument declares an FileNotFoundException and calls it “ex” catch(FileNotFoundException ex){ This is just like declaring any other argument

You can then call helpful methods from the exception class like: ex.printStackTrace(); This effectively prints a list of what method threw the exception, what method called that method, what method called that one...... all the way back to main We’ll talk about the stack later on in the lecture

Go with the flow How does a try catch block work? If this works... Program Control How does a try catch block work? FileReader fr; try{ fr = new FileReader(“myfile.txt”); char myChar = fr.read(); }catch(FileNotFoundException ex){ System.out.println(“Ooops!”); } If this works... ...this is never run

Go with the flow How does a try catch block work? Program Control How does a try catch block work? FileReader fr; try{ fr = new FileReader(“myfile.txt”); char myChar = fr.read(); }catch(FileNotFoundException ex){ System.out.println(“Ooops!”); } If this doesn’t work... This is not reached ...this is run

Bigger Blocks Methods can throw more than one type of exception: Method from ArrayList

Catching multiple Exceptions try{ readThisTextDocument(thisFile); }catch(EOFException e){ //The end of the file }catch(FileNotFoundException e){ //The file isn’t there }

Where to catch The JVM will check each catch block in turn from top to bottom try{ readThisTextDocument(); }catch(EOFException e){ //The end of the file }catch(FileNotFoundException e){ //The file isn’t there }

Polymorphic Exceptions are polymorphic If you catch a super class exception at the top, the JVM won’t keep checking for a more specific one try{ readThisTextDocument(); }catch(Exception e){ //Everything caught here }catch(EOFException e){ //The end of the file }catch(FileNotFoundException e){ //The file isn’t there }

Finally There is an optional ‘finally’ clause for a try catch block: FileReader fr; try{ fr = new FileReader(“myfile.txt”); char myChar = fr.read(); }catch(FileNotFoundException ex){ System.out.println(“Ooops!”); }finally{ System.out.println(“Do this anyway”); } System.out.println(myChar); This is mostly used to free up resources. You probably won’t use it often

Try catch is for exceptional circumstances External things that you can’t control Not for flaws in your code

Coming up Exceptions An Example The Throws keyword Try and Catch The flow Multiple exceptions Finally How exceptions are thrown What the complier checks Handle or Defer Recovery Writing your own

void go() throws NoFuelException A fictional system public Car{ public void go() throws NoFuelException{ if(fuel==0){ throw new NoFuelException(); } Car void go() throws NoFuelException public Person{ public void drive(Car c){ c.go() } Person void drive()

How it works The exception is always thrown back to the caller Throws an exception back Car Person Calls risky method Something goes wrong! No Fuel The exception is always thrown back to the caller

Coming up Exceptions An Example The Throws keyword Try and Catch The flow Multiple exceptions Finally How exceptions are thrown What the complier checks Handle or Defer Recovery Writing your own

The exception hierarchy There are many subclasses of exception..... AclNotFoundException, ActivationException, AlreadyBoundException, ApplicationException, AWTException, BackingStoreException, BadAttributeValueExpException, BadBinaryOpValueExpException, BadLocationException, BadStringOperationException, BrokenBarrierException, CertificateException, ClassNotFoundException, CloneNotSupportedException, DataFormatException, DatatypeConfigurationException, DestroyFailedException, ExecutionException, ExpandVetoException, FontFormatException, GeneralSecurityException, GSSException, IllegalAccessException, IllegalClassFormatException, InstantiationException, InterruptedException, IntrospectionException, InvalidApplicationException, InvalidMidiDataException, InvalidPreferencesFormatException, InvalidTargetObjectTypeException, InvocationTargetException, IOException, JMException, LastOwnerException, LineUnavailableException, MidiUnavailableException, MimeTypeParseException, NamingException, NoninvertibleTransformException, NoSuchFieldException, NoSuchMethodException, NotBoundException, NotOwnerException, ParseException, ParserConfigurationException, PrinterException, PrintException, PrivilegedActionException, PropertyVetoException, RefreshFailedException, RemarshalException, RuntimeException, SAXException, ServerNotActiveException, SQLException, TimeoutException, TooManyListenersException, TransformerException, UnmodifiableClassException, UnsupportedAudioFileException, UnsupportedCallbackException, UnsupportedFlavorException, UnsupportedLookAndFeelException, URISyntaxException, UserException, XAException, XMLParseException, XPathException

What the compiler checks Exceptions can be broadly categorised into Checked exceptions Unchecked exceptions When you call a method that could throw a checked exception, the compiler makes you handle it. You can either catch it, or defer it. We’ll cover deferring later.

What the compiler doesn’t check All subclasses of RuntimeException are Unchecked exceptions The compiler can’t guess what state the program is going to get into or what data it’ll get fed so it can’t check for runtime exceptions

What the compiler doesn’t check Runtime exceptions include ClassCastException IndexOutOfBoundsException, NegativeArraySizeException NullPointerException These are the exceptions you’ve probably seen. This is why you have never had to catch exceptions before

Checked and Unchecked Checked exceptions are likely to happen, and are out of your control, a broken drive, a network outage... An Unchecked exception occurrence is your fault! Perfect code should never throw an unchecked exception

Unchecked Exceptions Unchecked exceptions are normally thrown due to: Logic error in the code Undefensive programming – not making sure that your user has entered a number rather than a letter etc Checking user input is sensible is called sanitising inputs

What happens? When any exception is thrown The throwing method terminates immediately The program does not run the rest of the method body So methods that should return a value don’t have to return anything if they throw an exception

Coming up Exceptions An Example The Throws keyword Try and Catch The flow Multiple exceptions Finally How exceptions are thrown What the complier checks Handle or Defer Recovery Writing your own

Handling There are two ways to handle an exception deal with it here and now with a try catch block defer it, pass it to another method to fix This means passing it on to the method that called your method that called the method that threw the exception

Class that called your class Defer it What if Your class doesn’t want to deal with it? Defer it! Throw it on to the method that called yours Again? Throws an exception back Risky class Class that called your class Your class Calls risky method Something goes wrong!

Class that called that Class that called that Class that called that

Class containing main() If you don’t catch your exception by the time it is thrown back to the JVM, your program will terminate Class containing main() Class that called that JVM

An exception doesn’t need to be passed from class to class, it can be passed between methods in the same class Method that called that Method that called that Method that called that

Throwing public Car{ public void go() throws NoFuelException{ if(fuel==0){ throw new NoFuelException(); } How do I get a method to throw an exception that it has been thrown? Simple, you mark that method with the throws declaration public Person throws NoFuelException{ public void drive(Car c){ c.go() } public Person{ public void drive(Car c){ c.go() }

The Stack It’s time to look at the stack Now Eric talks

Coming up Exceptions An Example The Throws keyword Try and Catch The flow Multiple exceptions Finally How exceptions are thrown What the complier checks Handle or Defer Recovery Writing your own

Recovering from an exception So you have an exception thrown You tell the user their file isn’t there You have handled the error What now? Often you can use a loop to try the task again

Attempting a no fuel recovery boolean successful = false; int attempts = 0; do { try { person.drive(myCar); successful = true; } catch(NoFuelException e) { System.out.println(“no fuel in the car!”); attempts++; } while(!successful && attempts < MAX_ATTEMPTS); if(!successful) { Report the problem and give up;

Coming up Exceptions An Example The Throws keyword Try and Catch The flow Multiple exceptions Finally How exceptions are thrown What the complier checks Handle or Defer Recovery Writing your own

Writing your own You will probably spend more time catching other people’s exception than writing and throwing your own Subclass Exception for a checked exception Subclass RuntimeException for an unchecked exception

Coming up Exceptions An Example The Throws keyword Try and Catch The flow Multiple exceptions Finally How exceptions are thrown What the complier checks Handle or Defer Recovery Writing your own