COMP201 Java Programming Topic 6: Exceptions Reading: Chapter 11.

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 CSE301 University of Sunderland Harry Erwin, PhD.
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Exception Handling. Background In a perfect world, users would never enter data in the wrong form, files they choose to open would always exist, and code.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
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.
Index Exception handling Exception In Java Exception Types
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Java Exceptions. Exceptions Often in computing, operations cannot properly execute because some sort of error has occurred. Some examples: Often in computing,
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
For use of Cleveland State's IST410 Students only 1 Exception.
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.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
Exception Handling. Introduction An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
1 Lecture 4 Exception Handling. 2 Exception-Handling Fundamentals An exception is an abnormal condition that arises in a code sequence at run time A Java.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
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 in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
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.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Object Oriented Programming with Java (150704).  Throwable Exception (This class will catch exceptions generated by prog.) (Create your own custom exception.
Slides Credit Umair Javed LUMS Web Application Development.
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
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.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Unit 4 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
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.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
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.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
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.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
CS 61B Data Structures and Programming Methodology July 7, 2008 David Sun.
Geoff Holmes Week 5 problems Handling Throwing Catching Multiple exceptions Finally clause Examples 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 Chapter 9.
Chapter 12 Exception Handling
Exception Handling and Reading / Writing Files
Exception Handling Chapter 9 Edited by JJ.
Web Design & Development Lecture 7
Chapter 12 Exception Handling and Text IO Part 1
Java Basics Exception Handling.
Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

COMP201 Java Programming Topic 6: Exceptions Reading: Chapter 11

COMP201 Topic 7 / Slide 2 Objective/Outline l Objective: Study how to handle exceptions in java l Outline: n Introduction n Java exception classes (Checked vs unchecked exceptions) n Dealing with exceptions –Throwing exceptions –Catching exceptions

COMP201 Topic 7 / Slide 3 Introduction l Causes of errors l User input errors: typos, malformed URL, wrong file name, wrong info in file… l Hardware errors: Disk full, printer out of paper or down, web page unavailable… l Code errors: invalid array index, bad cast, read past end of file, pop empty stack, null object reference…

COMP201 Topic 7 / Slide 4 Introduction l Goals of error handling l Don’t want: l Want: l Return to a safe state and enable user to execute other commands l Allow user to save work and terminate program gracefully.

COMP201 Topic 7 / Slide 5 Introduction l Java exception handling mechanism: Every method is allowed to have two exit paths n No errors occur –Method exits in the normal way –Returns a value –Control passed to the calling code. n 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

COMP201 Topic 7 / Slide 6 Outline l Introduction l Java exception classes l Dealing with exceptions  Throwing exceptions  Catching exceptions

COMP201 Topic 7 / Slide 7 Java Exception Classes JVM internal errors l Java has many classes for error handling. They are called exception classes

COMP201 Topic 7 / Slide 8 Java Exception Classes java.io.IOException 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 checked java.io.EOFException …

COMP201 Topic 7 / Slide 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 l Those two exceptions are unchecked  JVM internal errors beyond your control  You should not allow logical errors at the first place

COMP201 Topic 7 / Slide 10 l All other exceptions (C++ runtime_error) are checked, i.e. you have to explicitly handle them. Otherwise compiler errors results in. n Trying to read pass end of file n Open a malformed URL n … AclNotFoundException, ActivationException, AWTException, BadLocationException, ClassNotFoundException, CloneNotSupportedException, DataFormatException, ExpandVetoException, GeneralSecurityException, IllegalAccessException, InstantiationException, InterruptedException, IntrospectionException, InvocationTargetException, IOException, LastOwnerException, … Checked exceptions Can be found in online API

COMP201 Topic 7 / Slide 11 Exceptions l Typically, what methods does an exception class have? n Check IOException

COMP201 Topic 7 / Slide 12 Java Exception Classes l 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 l Most programs throw and catch objects that derive from the Exception class

COMP201 Topic 7 / Slide 13 Outline l Introduction l Java exception classes l Dealing with exceptions  Throwing exceptions  Catching exceptions

COMP201 Topic 7 / Slide 14 Dealing with Exceptions l Need to consider exceptions when writing each method n Identifying possible exceptions –Check each line of code inside the method l If a method from someone else is called, check API to see if it throws exceptions l If some other method you wrote is called, also check to see if it throws exceptions. n Dealing with exceptions –If checked exceptions might be thrown at any point inside the method, you need to deal with it l Catching exceptions: Handle an exception in the current method. l Throwing exceptions: Don’t know how to handle an exception in the current method and need the caller method to deal with it.

COMP201 Topic 7 / Slide 15 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

COMP201 Topic 7 / Slide 16 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. l If you simply ignore it, compiler error results in. Try this. The nextToken method of StringTokenizer might throw NoSuchElementException. But it is not checked, so we don’t have to deal with it. NoSuchElementException Throwing Exceptions

COMP201 Topic 7 / Slide 17 l Notes: n Can throw multiple types of exceptions public void readData(BufferedReader in) throws IOException, EOFException n 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 Throwing Exceptions

COMP201 Topic 7 / Slide 18 Outline l Introduction l Java exception classes l Dealing with exceptions  Throwing exceptions  Catching exceptions

COMP201 Topic 7 / Slide 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 l 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.

COMP201 Topic 7 / Slide 20 Dealing with Exceptions l 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 ”.

COMP201 Topic 7 / Slide 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)

COMP201 Topic 7 / Slide 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

COMP201 Topic 7 / Slide 23 Dealing with Exceptions l Note that the following will produce a compiling error. Why? try {…} catch (Exception e3) {…} catch (ArithmeticException e1){…} catch (IOException e2) {…}

COMP201 Topic 7 / Slide 24 Catching Exceptions l 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?

COMP201 Topic 7 / Slide 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. l Useful in situations where resources must be released no matter what happened

COMP201 Topic 7 / Slide 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; } f(2) return 0 instead of 4! The finally clause

COMP201 Topic 7 / Slide 27 Dealing with Exceptions l 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.

COMP201 Topic 7 / Slide 28 C++ Notes l 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.