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

Slides:



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

Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
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.
Java Exception Very slightly modified from K.P. Chow University of Hong Kong (some slides from S.M. Yiu)
Index Exception handling Exception In Java Exception Types
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,
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
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.
Java Exceptions. Types of exceptions  Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
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.
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 Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系
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.
06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.
Java Review 2 – Errors, Exceptions, Debugging Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
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.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
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.
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:
Peyman Dodangeh Sharif University of Technology Fall 2013.
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
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.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
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.
Exceptions and Assertions Chapter 15 – CSCI 1302.
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.
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.
Java Programming: Exceptions1 Exceptions Reference: java.sun.com/docs/books/tutorial/essential/exceptions/
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.
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.
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
MIT AITI 2003 Lecture14 Exceptions
CS102 – Exceptions David Davenport Latest: May 2015
COMPSCI 230 S Programming Techniques
Exceptions 10-Nov-18.
Advanced Programming Behnam Hatami Fall 2017.
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.
ATS Application Programming: Java Programming
Exception Handling in Java
CS201: Data Structures and Discrete Mathematics I
Web Design & Development Lecture 7
Java Basics Exception Handling.
Presentation transcript:

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

交通大學資訊工程學系 蔡文能第2頁第2頁 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"); }

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

交通大學資訊工程學系 蔡文能第4頁第4頁 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).

交通大學資訊工程學系 蔡文能第5頁第5頁 JavaMore Java Examples Exception Handling: throw You can throw an exception 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()

交通大學資訊工程學系 蔡文能第6頁第6頁 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頁第7頁 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.

交通大學資訊工程學系 蔡文能第8頁第8頁 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).

交通大學資訊工程學系 蔡文能第9頁第9頁 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.

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

交通大學資訊工程學系 蔡文能第 11 頁 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"); }

交通大學資訊工程學系 蔡文能第 12 頁 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 an alternate return

交通大學資訊工程學系 蔡文能第 13 頁 JavaMore Java Examples Exception Enforcement In general, you do the following:  specify what exceptions each method can generate. (throw)  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.

交通大學資訊工程學系 蔡文能第 14 頁 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.

交通大學資訊工程學系 蔡文能第 15 頁 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.

交通大學資訊工程學系 蔡文能第 16 頁 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 }

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

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

交通大學資訊工程學系 蔡文能第 19 頁 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). User-defined Exception Type class FooException extends Exception { } //.. class BlahException extends Exception { BlahException(){} BlahException(String s) { super(s); } } //.. throw new BlahException("Invalid blah");

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

交通大學資訊工程學系 蔡文能第 21 頁 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.

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