MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Yoshi
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
Java Exception Very slightly modified from K.P. Chow University of Hong Kong (some slides from S.M. Yiu)
COMP 121 Week 5: Exceptions and Exception Handling.
Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT What data does.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
For use of Cleveland State's IST410 Students only 1 Exception.
Java Programming Exceptions. Java has a built in mechanism for error handling and trapping errors Usually this means dealing with abnormal events or code.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Java Exceptions. Types of exceptions  Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot.
Testing and Error Handling Intro to Java. Testing We test to try and make sure our programs work correctly and have no bugs If we have access to the code,
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
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.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
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.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Chapter 9: Exceptions For error/problem situations Exception classes –ArithmeticException, IOException, etc. –checked exceptions try blocks –catch statements.
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 }
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Practice Session 9 Exchanger CyclicBarrier Exceptions.
1 cuberoot /* Solve f(x) = x*x*x-5 = 0 f'(x) = 3x^2 */ public class cuberoot{ public static void main(String args[]){ double error= ; double x0.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
EXCEPTIONS There's an exception to every rule.. 2 Introduction: Methods  The signature of a method includes  access control modifier  return type 
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
LECTURE 8: EXCEPTIONS CSC 212 – Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
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.
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.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Java Exceptions a quick review….
Exceptions In this lecture:
Chapter 10 – Exception Handling
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Introduction Exception handling Exception Handles errors
Introduction to Exceptions in Java
CSE 501N Fall ’09 17: Exception Handling
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.
Web Design & Development Lecture 7
Java Exceptions Dan Fleck CS211.
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Tutorial Exceptions Handling.
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.
Tutorial MutliThreading.
Java Basics Exception Handling.
Presentation transcript:

MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions

Attack of the Exception What happens when this method is used to take the average of an array of length zero? Program throws an Exception and fails java.lang.ArithmeticException: / by zero public static int average(int[] a) { int total = 0; for(int i = 0; i < a.length; i++) { total += a[i]; } return total / a.length; }

What is an Exception? An error event that disrupts the program flow and may cause a program to fail. Some examples: Performing illegal arithmetic Illegal arguments to methods Accessing an out-of-bounds array element Hardware failures Writing to a read-only file

Another Exception Example What is the output of this program? public class ExceptionExample { public static void main(String args[]) { String[] greek = {"Alpha", "Beta"}; System.out.println(greek[2]); } Output: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at ExceptionExample.main(ExceptionExample.java:4)

Exception Message Details What exception class? Which array index is out of bounds? What method throws the exception? What file contains the method? What line of the file throws the exception? Exception message format: [exception class]: [additional description of exception] at [class].[method]([file]:[line number]) Example: java.lang.ArrayIndexOutOfBoundsException: 2 at ExceptionExample.main(ExceptionExample.java:4) ArrayIndexOutOfBoundsException 2 main ExceptionExample.java 4

Exception Handling Use a try-catch block to handle exceptions that are thrown try { // code that might throw exception } catch ([Type of Exception] e) { // what to do if exception is thrown }

Exception Handling Example public static int average(int[] a) { int total = 0; for(int i = 0; i < a.length; i++) { total += a[i]; } return total / a.length; } public static void printAverage(int[] a) { try { int avg = average(a); System.out.println("the average is: " + avg); } catch (ArithmeticException e) { System.out.println("error calculating average"); }

Catching Multiple Exceptions Handle multiple possible exceptions by multiple successive catch blocks try { // code that might throw multiple exception } catch (IOException e) { // handle IOException and all subclasses } catch (ClassNotFoundException e2) { // handle ClassNotFoundException }

Exceptions Terminology When an exception happens we say it was thrown or raised When an exception is dealt with, we say the exception is was handled or caught

Unchecked Exceptions All the exceptions we've seen so far have been Unchecked Exceptions, or Runtime Exceptions Usually occur because of programming errors, when code is not robust enough to prevent them They are numerous and can be ignored by the programmer

Common Unchecked Exceptions NullPointerException reference is null and should not be IllegalArgumentException method argument is improper is some way IllegalStateException method called when class is in improper state

Checked Exceptions There are also Checked Exceptions Usually occur because of errors programmer cannot control: examples: hardware failures, unreadable files They are less frequent and they cannot be ignored by the programmer...

Dealing With Checked Exceptions Every method must catch (handle) checked exceptions or specify that it may throw them Specify with the throws keyword void readFile(String filename) { try { FileReader reader = new FileReader("myfile.txt"); // read from file... } catch (FileNotFoundException e) { System.out.println("file was not found"); } void readFile(String filename) throws FileNotFoundException { FileReader reader = new FileReader("myfile.txt"); // read from file... } or

Exception Class Hierarchy Exception RuntimeException ArrayIndexOutofBounds NullPointerException IllegalArgumentException etc. IOException FileNotFoundException MalformedURLException SocketException etc. SQLException Unchecked Exceptions Checked Exceptions All exceptions are instances of classes that are subclasses of Exception

Checked and Unchecked Exceptions Checked ExceptionUnchecked Exception not subclass of RuntimeException subclass of RuntimeException if not caught, method must specify it to be thrown if not caught, method may specify it to be thrown for errors that the programmer cannot directly prevent from occurring for errors that the programmer can directly prevent from occurring, IOException, FileNotFoundException, SocketException NullPointerException, IllegalArgumentException, IllegalStateException

Exception Constructors Exceptions have at least two constructors: 1. no arguments NullPointerException e = new NullPointerException(); 2. single String argument descriptive message that appears when exception error message is printed IllegalArgumentExceptione e = new IllegalArgumentException("number must be positive");

Writing Your Own Exception To write your own exception, write a subclass of Exception and write both types of constructors public class MyCheckedException extends IOException { public MyCheckedException() {} public MyCheckedException(String m) {super(m);} } public class MyUncheckedException extends RuntimeException { public MyUncheckedException() {} public MyUncheckedException(String m) {super(m);} }

Throwing Exceptions Throw exception with the throw keyword public static int average(int[] a) { if (a.length == 0) { throw new IllegalArgumentException("array is empty"); } int total = 0; for(int i = 0; i < a.length; i++) { total += a[i]; } return total / a.length; }

Keyword Summary Four new Java keywords try and catch – used to handle exceptions that may be thrown throws – to specify which exceptions a method throws in method declaration throw – to throw an exception

Throws and Inheritance A method can throw less exceptions, but not more, than the method it is overriding public class MyClass { public void doSomething() throws IOException, SQLException { // do something here } public class MySubclass extends MyPlay { public void doSomething() throws IOException { // do something here }

Line Intersection Example Consider this class Line, which has two fields, a slope and a yIntercept Let's write an intersect method that returns the x-coordinate at which the two lines intersect. sig Line { private double slope; private double yIntercept; double getSlope() { return slope; } double getYIntercept() { return yIntercept; } }

Calculating the x-coordinate at which two lines intersect We could translate this directly into the following intersect method: Boring Math Stuff... y = m 1 x + b 1 y = m 2 x + b 2 m 1 x + b 1 = m 2 x + b 2 m 1 x - m 2 x = b 2 - b 1 (m 1 - m 2 )x = b 2 - b 1 x = (b 2 - b 1 )/(m 1 - m 2 ) double intersect(Line line1, Line line2) { return (line2.getYIntercept() – line1.yIntercept()) / (line1.slope() – line2.slope()) }

Parallel lines will never intersect. If lines are parallel, then their slopes will be equal, line1.slope() – line2.slope() = 0, and our method will attempt to divide by zero Let's write a new exception ParallelException to throw when this occurs. What About Parallel Lines?

ParallelException ParallelException will be a checked exception because calculating whether lines are parallel is not something we expect the programmer to know how to do and prevent in advance. Checked exceptions are a subclass of Exception, but not RuntimeException public class ParallelException extends Exception { public ParallelException() {} public ParallelException(String msg) { super(msg); } }

Final Intersect Method Because it is a checked exception, intersect must specify that it throws it double intersect(Line line1, Line line2) throws ParallelException { if (line1.slope() = line2.slope()) { throw new ParallelException(); } return (line2.getYIntercept() – line1.yIntercept()) / (line1.slope() – line2.slope()) }

Calling the intersect Method A method that accepts two Lines as arguments, calls intersect, and prints out the results: void printIntersect(Line line1, Line line2) { try { double x = intersect(line1, line2); System.out.println("Intersect at " + x); } catch (ParallelException e) { System.out.println("They are parallel"); }