交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系

Slides:



Advertisements
Similar presentations
Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Advertisements

Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Exception Handling. Introduction Errors can be dealt with at place error occurs –Easy to see if proper error checking implemented –Harder to read application.
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.
Index Exception handling Exception In Java Exception Types
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.
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.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Exceptions and Exception Handling Carl Alphonce CSE116.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
Objectives Understanding what an exception is Understanding the heirarchy of exception classes Learn the types of exception and how to catch and handle.
Exceptions and Exception Handling (1) Carl Alphonce CSE116.
Java Exceptions, Cloning, Serialization Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
交通大學資訊工程學系 Programming in Java Exception Handling 蔡文能 交通大學資訊工程學系
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.
© Copyright Eliyahu Brutman Exceptions. © Copyright Eliyahu Brutman Exceptions and Design Patterns - 2 Introduction to Exception Handling Definition:
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
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.
Object Oriented Programming
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
CIS 270—Application Development II Chapter 13—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.
Slides Credit Umair Javed LUMS Web Application Development.
Exceptions 1. Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException:
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
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.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
COP4020 Programming Languages Exception Handling Prof. Robert van Engelen (modified by Prof. Em. Chris Lacher)
ICS 313: Programming Language Theory Chapter 14: Exceptions.
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.
1 1. Normal and exceptional control flow 2. Java exception types 3. Exception handling syntax 4. Inheritance.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
Java Programming: Exceptions1 Exceptions Reference: java.sun.com/docs/books/tutorial/essential/exceptions/
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.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
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.
© 2001 by Ashby M. Woolf Revision 2 Exceptions for Exceptional Circumstances Passing a Problem up the Chain of Command.
Section 3.3 Exceptional Situations. 3.3 Exceptional Situations Exceptional situation Associated with an unusual, sometimes unpredictable event, detectable.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Java Exceptions a quick review….
Chapter 10 – Exception Handling
CS102 – Exceptions David Davenport Latest: May 2015
ATS Application Programming: Java Programming
Exception Handling in Java
Web Design & Development Lecture 7
Java Basics Exception Handling.
Exception Handling and Event Handling
CMSC 202 Exceptions.
Presentation transcript:

交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系

交通大學資訊工程學系 蔡文能 7- 第 2 頁 JavaMore Java Examples Agenda Exception handling Exception handling in Java Exception handling in C++

交通大學資訊工程學系 蔡文能 7- 第 3 頁 JavaMore Java Examples Exception? exception  An exception is any unusual event, either erroneous or not, detectable by either hardware or software, that may require special processing exception handling  Without exception handling  When an exception occurs, control goes to the operating system, where typically an error message is displayed the program is terminated With exception handling  Programs are allowed to trap exceptions  There is a possibility to fix the problem and continuing execution

交通大學資訊工程學系 蔡文能 7- 第 4 頁 JavaMore Java Examples What to do when Exception occurs? There are several ways a function may react when encountering an unexpected/erroneous situation (i.e., Exception )  Terminate the program Cannot be used in a program that cannot afford to crash  Return a value representing “error”  Raise a flag Many standard C library functions used global variable errno  Need to check the flag after every operation  Losses information  Call a function supplied to be called in case of error Raise a signal / Event How will it handle the error? char* String::getString(); //ok: return NUKK on error int atoi(const char *); //what to return for “bad-str”?

交通大學資訊工程學系 蔡文能 7- 第 5 頁 JavaMore Java Examples When To Use Exceptions Required by compiler when using some statements (Java) Make code safer (catch fatal errors)‏ Fix the problem and try again Patch the problem and continue Make a complex error mechanism simpler

交通大學資訊工程學系 蔡文能 7- 第 6 頁 JavaMore Java Examples Exception example try { readFromFile("datafile"); } catch (FileNotFoundException e) { System.err.println("Error: File not found"); } try { readFromFile("datafile"); } catch (FileNotFoundException e) { System.err.println("Error: File not found"); }

交通大學資訊工程學系 蔡文能 7- 第 7 頁 JavaMore Java Examples Exception Handling: Some Options Print something Throw a new exception Re-Throw the exception Fix the problem Exit

交通大學資訊工程學系 蔡文能 7- 第 8 頁 JavaMore Java Examples Exception Handling: Printing You can print a stack trace by calling the exception method printStackTrace() Sometimes it's better to send error messages to stderr :  System.err.println("Error: invalid thingy"); Some applications log error messages  file  logging service (syslog).

交通大學資訊工程學系 蔡文能 7- 第 9 頁 JavaMore Java Examples Throwing Objects Why throw an object?  Additional data encapsulated  An object is created upon invoking the throw statement  Can be created with additional data, passed to Ctor  Object is destroyed after the catch clause ends

交通大學資訊工程學系 蔡文能 7- 第 10 頁 JavaMore Java Examples Exception Handling: throw You can throw an exception (object) from an exception handler (a catch block). Allows you to change exception type and/or error message. You can also alter the base of the stack trace fillInStackTrace()

交通大學資訊工程學系 蔡文能 7- 第 11 頁 JavaMore Java Examples Exception Handling: Re- throw You can throw an exception from an exception handler (a catch block) without changing anything: called rethrowing The caller needs to deal with the exception. This also happens if you don't catch the exception! sometimes you need to take some action and then rethrow the exception.

交通大學資訊工程學系 蔡文能 7- 第 12 頁 JavaMore Java Examples Another way to re-throw You can allow selected types of exceptions to be propogated to the caller of your method: void blah() throws IOException { Within blah() you don't need to catch these exceptions (to be able to compile).

交通大學資訊工程學系 蔡文能 7- 第 13 頁 JavaMore Java Examples Exception example public class ThrowUp { public static void main(String[ ] args) { String tmp; try { // generate an ArrayIndexOutOfBoundsExceptions.. //.. (on purpose!). for (int i=0 ; i<args.length+10 ; i++) { tmp = args[i]; } System.out.println("I made it!"); } catch (ArrayIndexOutOfBoundsException up) { throw new SecurityException("Trouble"); } } // main }

交通大學資訊工程學系 蔡文能 7- 第 14 頁 JavaMore Java Examples Exception Handling: Fix the problem. You can't fix things and then resume execution automatically you can do this in C++. You can have a loop the retries the code again.

交通大學資訊工程學系 蔡文能 7- 第 15 頁 JavaMore Java Examples Exception Handling: exiting Sometimes the error is fatal, and you want to stop the program immediately. System.exit();

交通大學資訊工程學系 蔡文能 7- 第 16 頁 JavaMore Java Examples Wait.java public class Wait { public static void main(String[ ] args) { boolean done=false; int seconds=0; try { seconds = Integer.parseInt(args[0]); } catch (Exception e) { System.out.println("Please specify the number of seconds"); System.exit(1); } long initialtime = System.currentTimeMillis( ); while (!done) { try { if (System.currentTimeMillis()-initialtime < seconds*1000) throw new Exception("Not Yet - keep trying"); done=true; } catch (Exception e) { System.out.println(e); } System.out.println("Done!\n"); }

交通大學資訊工程學系 蔡文能 7- 第 17 頁 JavaMore Java Examples How/when do you generate exceptions? Use throw: throw new Exception("broken!"); You can use throw anywhere.  you detect some error that means the following code should not be executed. In some cases, you can think of throw as a alternate return

交通大學資訊工程學系 蔡文能 7- 第 18 頁 JavaMore Java Examples Exception Enforcement In general, you do the following:  specify what exceptions each method can generate.  write code to catch all exceptions that can be generated by a method call. The compiler (usually) enforces this  it is a compilation error to call a method without catching it's declared exception types.

交通大學資訊工程學系 蔡文能 7- 第 19 頁 JavaMore Java Examples RunTime Exceptions There are exceptions that are generated by the system (that are usually caused by programming mistakes):  NullPointerException (null references)  ArrayIndexOutOfBoundsException If you don't catch these, a stack trace will be generated and the program will terminate. The compiler does not force you to catch these exceptions.

交通大學資訊工程學系 蔡文能 7- 第 20 頁 JavaMore Java Examples Exception Types Exceptions are objects! Exception types are classes.  A (quite large!) hierarchy of classes. All exception types are derived from the class Exception  there are some methods defined in this base class.

交通大學資訊工程學系 蔡文能 7- 第 21 頁 JavaMore Java Examples NullPointer.java import java.util.*; public class NullPointer { public static void main(String[ ] args) { Date f = new Date(); f=null; PrintSomething2(f); // comment out to test PrintSomething PrintSomething(f); } // no checks, if x is null runtime exception default behavior static void PrintSomething(Object x) { System.out.println(x.getClass( ).getName()); } // we explicitly check for runtime exception! static void PrintSomething2(Object x) { try { System.out.println(x.getClass().getName()); } catch (RuntimeException re) { System.out.println("Fatal Error!"); System.exit(1); } } // main }

交通大學資訊工程學系 蔡文能 7- 第 22 頁 JavaMore Java Examples Throwable Exception Error RunTimeException NullPointerException ArithmeticException IOException Exception Type Hierarchy (partial) EOFException VirtualMachineError

交通大學資訊工程學系 蔡文能 7- 第 23 頁 JavaMore Java Examples Some Exception Methods These are actually inherited from throwable printStackTrace() fillInStackTrack() getMessage()

交通大學資訊工程學系 蔡文能 7- 第 24 頁 JavaMore Java Examples Creating Your Own Exception Types It is often useful to create your own type of exception.  generally all you create is a name.  you can get fancy and add new methods to your exception class(es).

交通大學資訊工程學系 蔡文能 7- 第 25 頁 JavaMore Java Examples User-defined Exception Type class FooException extends Exception {} //.. class BlahException extends Exception { BlahException(){} BlahException(String s) { super(s); } } //.. throw new BlahException("Invalid blah");

交通大學資訊工程學系 蔡文能 7- 第 26 頁 JavaMore Java Examples using finally try { statements... } catch (ExceptionType1 ename1) { error handling statements... } catch (ExceptionType2 ename2) { error handling statements... } finally { … this code always executed … }

交通大學資訊工程學系 蔡文能 7- 第 27 頁 JavaMore Java Examples Why finally ? What is there to clean up?  No memory cleanup required in Java!  No destructors to call! Sometimes you need to set the state of things (fields) to some stable (acceptable) state.

交通大學資訊工程學系 蔡文能 7- 第 28 頁 JavaMore Java Examples Exception Handling again 謝謝捧場 蔡文能