Chapter SeventeenModern Programming Languages1 A Third Look At Java.

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.
Yoshi
4/29/20151 Java Exceptions. 4/29/20152 Overview An exception is an unusual circumstance, such as an error condition, that must be handled in a non-standard.
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
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.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
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.
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
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.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
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.
E XCEPTION H ANDLING Chapter 11 C S 442: A DVANCED J AVA P ROGRAMMING.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
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.
11-Jun-15 Exceptions. 2 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.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
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. 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.
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.
A Third Look At Java Chapter SeventeenModern Programming Languages, 2nd ed.1.
Object Oriented Programming
Chapter 12: Exception Handling
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.
Slides Credit Umair Javed LUMS Web Application Development.
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.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
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.
Android How to Program, 2/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
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.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
Exceptions and Assertions Chapter 15 – CSCI 1302.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
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.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
EXCEPTIONS There's an exception to every rule.. 2 Introduction: Methods  The signature of a method includes  access control modifier  return type 
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
Java Programming: Exceptions1 Exceptions Reference: java.sun.com/docs/books/tutorial/essential/exceptions/
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
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.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
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.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Exceptions 10-Nov-18.
Advanced Programming Behnam Hatami Fall 2017.
Exception Handling Chapter 9.
Exception Handling Chapter 9 Edited by JJ.
Exceptions 10-May-19.
Java Basics Exception Handling.
Exception Handling.
Presentation transcript:

Chapter SeventeenModern Programming Languages1 A Third Look At Java

Chapter SeventeenModern Programming Languages2 A Little Demo public class Test { public static void main(String[] args) { int i = Integer.parseInt(args[0]); int j = Integer.parseInt(args[1]); System.out.println(i/j); } } > javac Test.java > java Test >

Chapter SeventeenModern Programming Languages3 Exceptions > java Test Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Test.main(Test.java:3) > java Test 6 0 Exception in thread "main" java.lang.ArithmeticException: / by zero at Test.main(Test.java:4) In early languages, that’s all that happened: error message, core dump, terminate. Modern languages like Java support exception handling.

Chapter SeventeenModern Programming Languages4 Outline n 17.2 Throwable classes n 17.3 Catching exceptions n 17.4 Throwing exceptions n 17.5 Checked exceptions n 17.6 Error handling n 17.7 Finally n 17.8 Farewell to Java

Chapter SeventeenModern Programming Languages5 Some Predefined Exceptions Java ExceptionCode to Cause It NullPointerExceptionString s = null; s.length(); ArithmeticExceptionint a = 3; int b = 0; int q = a/b; ArrayIndexOutOfBoundsExceptionint[] a = new int[10]; a[10]; ClassCastExceptionObject x = new Integer(1); String s = (String) x; StringIndexOutOfBoundsExceptionString s = "Hello"; s.charAt(5);

Chapter SeventeenModern Programming Languages6 An Exception Is An Object The names of exceptions are class names, like NullPointerException n Exceptions are objects of those classes n In the previous examples, the Java language system automatically creates an object of an exception class and throws it n If the program does not catch it, it terminates with an error message

Chapter SeventeenModern Programming Languages7 Throwable Classes To be thrown as an exception, an object must be of a class that inherits from the predefined class Throwable n There are four important predefined classes in that part of the class hierarchy: – Throwable – Error – Exception – RuntimeException

Chapter SeventeenModern Programming Languages8 Java will only throw objects of a class descended from Throwable Classes derived from Error are used for serious, system- generated errors, like OutOfMemoryError, that usually cannot be recovered from Classes derived from Exception are used for ordinary errors that a program might want to catch and recover from Classes derived from RuntimeException are used for ordinary system- generated errors, like ArithmeticException

Chapter SeventeenModern Programming Languages9 Outline n 17.2 Throwable classes n 17.3 Catching exceptions n 17.4 Throwing exceptions n 17.5 Checked exceptions n 17.6 Error handling n 17.7 Finally n 17.8 Farewell to Java

Chapter SeventeenModern Programming Languages10 The try Statement n Simplified… full syntax later The is a throwable class name Does the try part Does the catch part only if the try part throws an exception of the given ::= ::= try ::= catch ( )

Chapter SeventeenModern Programming Languages11 Example public class Test { public static void main(String[] args) { try { int i = Integer.parseInt(args[0]); int j = Integer.parseInt(args[1]); System.out.println(i/j); } catch (ArithmeticException a) { System.out.println("You're dividing by zero!"); } } } This will catch and handle any ArithmeticException. Other exceptions will still get the language system’s default behavior.

Chapter SeventeenModern Programming Languages12 Example n Catch type chooses exceptions to catch: – ArithmeticException got zero division – RuntimeException would get both examples above – Throwable would get all possible exceptions > java Test > java Test 6 0 You're dividing by zero! > java Test Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Test.main(Test.java:3)

Chapter SeventeenModern Programming Languages13 After The try Statement A try statement can be just another in a sequence of statements If no exception occurs in the try part, the catch part is not executed If no exception occurs in the try part, or if there is an exception which is caught in the catch part, execution continues with the statement following the try statement

Chapter SeventeenModern Programming Languages14 Exception Handled System.out.print("1, "); try { String s = null; s.length(); } catch (NullPointerException e) { System.out.print("2, "); } System.out.println("3"); This just prints the line 1, 2, 3

Chapter SeventeenModern Programming Languages15 Throw From Called Method The try statement gets a chance to catch exceptions thrown while the try part runs That includes exceptions thrown by methods called from the try part

Chapter SeventeenModern Programming Languages16 Example If g throws an ArithmeticException, that it does not catch, f will get it n In general, the throw and the catch can be separated by any number of method invocations void f() { try { g(); } catch (ArithmeticException a) { … } }

Chapter SeventeenModern Programming Languages17 If z throws an exception it does not catch, z ’s activation stops… …then y gets a chance to catch it; if it doesn’t, y ’s activation stops… …and so on all the way back to f

Chapter SeventeenModern Programming Languages18 Long-Distance Throws n That kind of long-distance throw is one of the big advantages of exception handling n All intermediate activations between the throw and the catch are stopped and popped n If not throwing or catching, they need not know anything about it

Chapter SeventeenModern Programming Languages19 Multiple catch Parts To catch more than one kind of exception, a catch part can specify some general superclass like RuntimeException But usually, to handle different kinds of exceptions differently, you use multiple catch parts ::= ::= try ::= | ::= catch ( )

Chapter SeventeenModern Programming Languages20 Example public static void main(String[] args) { try { int i = Integer.parseInt(args[0]); int j = Integer.parseInt(args[1]); System.out.println(i/j); } catch (ArithmeticException a) { System.out.println("You're dividing by zero!"); } catch (ArrayIndexOutOfBoundsException a) { System.out.println("Requires two parameters."); } } This will catch and handle both ArithmeticException and ArrayIndexOutOfBoundsException

Chapter SeventeenModern Programming Languages21 Example public static void main(String[] args) { try { int i = Integer.parseInt(args[0]); int j = Integer.parseInt(args[1]); System.out.println(i/j); } catch (ArithmeticException a) { System.out.println("You're dividing by zero!"); } catch (ArrayIndexOutOfBoundsException a) { System.out.println("Requires two parameters."); } catch (RuntimeException a) { System.out.println("Runtime exception."); } }

Chapter SeventeenModern Programming Languages22 Overlapping Catch Parts If an exception from the try part matches more than one of the catch parts, only the first matching catch part is executed A common pattern: catch parts for specific cases first, and a more general one at the end Note that Java does not allow unreachable catch parts, or unreachable code in general

Chapter SeventeenModern Programming Languages23 Outline n 17.2 Throwable classes n 17.3 Catching exceptions n 17.4 Throwing exceptions n 17.5 Checked exceptions n 17.6 Error handling n 17.7 Finally n 17.8 Farewell to Java

Chapter SeventeenModern Programming Languages24 The throw Statement n Most exceptions are thrown automatically by the language system n Sometimes you want to throw your own The is a reference to a throwable object—usually, a new one: ::= throw ; throw new NullPointerException();

Chapter SeventeenModern Programming Languages25 Custom Throwable Classes public class OutOfGas extends Exception { } System.out.print("1, "); try { throw new OutOfGas(); } catch (OutOfGas e) { System.out.print("2, "); } System.out.println("3");

Chapter SeventeenModern Programming Languages26 Using The Exception Object n The exception that was thrown is available in the catch block—as that parameter n It can be used to communicate information from the thrower to the catcher All classes derived from Throwable inherit a method printStackTrace They also inherit a String field with a detailed error message, and a getMessage method to access it

Chapter SeventeenModern Programming Languages27 Example public class OutOfGas extends Exception { public OutOfGas(String details) { super(details); } } try { throw new OutOfGas("You have run out of gas."); } catch (OutOfGas e) { System.out.println(e.getMessage()); } This calls a base-class constructor to initialize the field returned by getMessage().

Chapter SeventeenModern Programming Languages28 About super In Constructors The first statement in a constructor can be a call to super (with parameters, if needed) n That calls a base class constructor n Used to initialize inherited fields All constructors (except in Object ) start with a call to another constructor—if you don’t include one, Java calls super() implicitly

Chapter SeventeenModern Programming Languages29 More About Constructors n Also, all classes have at least one constructor—if you don’t include one, Java provides a no-arg constructor implicitly public class OutOfGas extends Exception { } public class OutOfGas extends Exception { public OutOfGas() { super(); } } These are equivalent!

Chapter SeventeenModern Programming Languages30 public class OutOfGas extends Exception { private int miles; public OutOfGas(String details, int m) { super(details); miles = m; } public int getMiles() { return miles; } } try { throw new OutOfGas("You have run out of gas.",19); } catch (OutOfGas e) { System.out.println(e.getMessage()); System.out.println("Odometer: " + e.getMiles()); }

Chapter SeventeenModern Programming Languages31 Outline n 17.2 Throwable classes n 17.3 Catching exceptions n 17.4 Throwing exceptions n 17.5 Checked exceptions n 17.6 Error handling n 17.7 Finally n 17.8 Farewell to Java

Chapter SeventeenModern Programming Languages32 Checked Exceptions This method will not compile: “The exception OutOfGas is not handled” n Java has not complained about this in our previous examples—why now? n Java distinguishes between two kinds of exceptions: checked and unchecked void z() { throw new OutOfGas("You have run out of gas.", 19"); }

Chapter SeventeenModern Programming Languages33 Checked Exceptions The checked exception classes are Exception and its descendants, excluding RuntimeException and its descendants

Chapter SeventeenModern Programming Languages34 What Gets Checked? n A method that can get a checked exception is not permitted to ignore it n It can catch it – That is, the code that generates the exception can be inside a try statement with a catch part for that checked exception n Or, it can declare that it does not catch it – Using a throws clause

Chapter SeventeenModern Programming Languages35 The Throws Clause A throws clause lists one or more throwable classes separated by commas n This one always throws, but in general, the throws clause means might throw So any caller of z must catch OutOfGas, or place it in its own throws clause void z() throws OutOfGas { throw new OutOfGas("You have run out of gas.", 19); }

Chapter SeventeenModern Programming Languages36 If z declares that it throws OutOfGas … …then y must catch it, or declare it throws it too… …and so on all the way back to f

Chapter SeventeenModern Programming Languages37 Why Use Checked Exceptions The throws clause is like documentation: it tells the reader that this exception can result from a call of this method n But it is verified documentation; if any checked exception can result from a method call, the compiler will insist it be declared n This can make programs easier to read and more likely to be correct

Chapter SeventeenModern Programming Languages38 How To Avoid Checked Exceptions You can always define your own exceptions using a different base class, such as Error or Throwable n Then they will be unchecked n Weigh the advantages carefully

Chapter SeventeenModern Programming Languages39 Outline n 17.2 Throwable classes n 17.3 Catching exceptions n 17.4 Throwing exceptions n 17.5 Checked exceptions n 17.6 Error handling n 17.7 Finally n 17.8 Farewell to Java

Chapter SeventeenModern Programming Languages40 Handling Errors n Example: popping an empty stack n Techniques: – Preconditions only – Total definition – Fatal errors – Error flagging – Using exceptions

Chapter SeventeenModern Programming Languages41 Preconditions Only n Document preconditions necessary to avoid errors n Caller must ensure these are met, or explicitly check if not sure

Chapter SeventeenModern Programming Languages42 /** * Pop the top int from this stack and return it. * This should be called only if the stack is * not empty. the popped int */ public int pop() { Node n = top; top = n.getLink(); return n.getData(); } if (s.hasMore()) x = s.pop(); else …

Chapter SeventeenModern Programming Languages43 Drawbacks If the caller makes a mistake, and pops an empty stack: NullPointerException – If that is uncaught, program crashes with an unhelpful error message – If caught, program relies on undocumented internals; an implementation using an array would cause a different exception

Chapter SeventeenModern Programming Languages44 Total Definition We can change the definition of pop so that it always works n Define some standard behavior for popping an empty stack n Like character-by-character file I/O in C: an EOF character at the end of the file n Like IEEE floating-point: NaN and signed infinity results

Chapter SeventeenModern Programming Languages45 /** * Pop the top int from this stack and return it. * If the stack is empty we return 0 and leave the * stack empty. the popped int, or 0 if the stack is empty */ public int pop() { Node n = top; if (n==null) return 0; top = n.getLink(); return n.getData(); }

Chapter SeventeenModern Programming Languages46 Drawbacks n Can mask important problems n If a client pops more than it pushes, this is probably a serious bug that should be detected and fixed, not concealed

Chapter SeventeenModern Programming Languages47 Fatal Errors n The old-fashioned approach: just crash! n Preconditions, plus decisive action n At least this does not conceal the problem…

Chapter SeventeenModern Programming Languages48 /** * Pop the top int from this stack and return it. * This should be called only if the stack is * not empty. If called when the stack is empty, * we print an error message and exit the program. the popped int */ public int pop() { Node n = top; if (n==null) { System.out.println("Popping an empty stack!"); System.exit(-1); } top = n.getLink(); return n.getData(); }

Chapter SeventeenModern Programming Languages49 Drawbacks n Not an object-oriented style: an object should do things to itself, not to the rest of the program n Inflexible: different clients may want to handle the error differently – Terminate – Clean up and terminate – Repair the error and continue – Ignore the error – Etc.

Chapter SeventeenModern Programming Languages50 Error Flagging n The method that detects the error can flag it somehow – By returning a special value (like C malloc ) – By setting a global variable (like C errno ) – By setting an instance variable to be checked by a method call (like C ferror(f) ) n Caller must explicitly test for error

Chapter SeventeenModern Programming Languages51 /** * Pop the top int from this stack and return it. * This should be called only if the stack is * not empty. If called when the stack is empty, * we set the error flag and return an undefined * value. the popped int if stack not empty */ public int pop() { Node n = top; if (n==null) { error = true; return 0; } top = n.getLink(); return n.getData(); }

Chapter SeventeenModern Programming Languages52 /** * Return the error flag for this stack. The error * flag is set true if an empty stack is ever popped. * It can be reset to false by calling resetError(). the error flag */ public boolean getError() { return error; } /** * Reset the error flag. We set it to false. */ public void resetError() { error = false; }

Chapter SeventeenModern Programming Languages53 /** * Pop the two top integers from the stack, divide * them, and push their integer quotient. There * should be at least two integers on the stack * when we are called. If not, we leave the stack * empty and set the error flag. */ public void divide() { int i = pop(); int j = pop(); if (getError()) return; push(i/j); } The kind of explicit error check required by an error flagging technique. Note that divide ’s caller may also have to check it, and its caller, and so on…

Chapter SeventeenModern Programming Languages54 Using Exceptions n The method that first finds the error throws an exception n May be checked or unchecked n Part of the documented behavior of the method

Chapter SeventeenModern Programming Languages55 /** * Pop the top int from this stack and return it. the popped int EmptyStack if stack is empty */ public int pop() throws EmptyStack { Node n = top; if (n==null) throw new EmptyStack(); top = n.getLink(); return n.getData(); }

Chapter SeventeenModern Programming Languages56 /** * Pop the two top integers from the stack, divide * them, and push their integer quotient. EmptyStack if stack runs out */ public void divide() throws EmptyStack { int i = pop(); int j = pop(); push(i/j); } Caller makes no error check—just passes the exception along if one occurs

Chapter SeventeenModern Programming Languages57 Advantages n Good error message even if uncaught n Documented part of the interface n Error caught right away, not masked n Caller need not explicitly check for error n Error can be ignored or handled flexibly

Chapter SeventeenModern Programming Languages58 Outline n 17.2 Throwable classes n 17.3 Catching exceptions n 17.4 Throwing exceptions n 17.5 Checked exceptions n 17.6 Error handling n 17.7 Finally n 17.8 Farewell to Java

Chapter SeventeenModern Programming Languages59 The Full try Syntax There is an optional finally part No matter what happens, the finally part is always executed at the end of the try statement ::= | | ::= try ::= | ::= catch ( ) ::= finally

Chapter SeventeenModern Programming Languages60 Using finally The finally part is usually used for cleanup operations n Whether or not there is an exception, the file is closed file.open(); try { workWith(file); } finally { file.close(); }

Chapter SeventeenModern Programming Languages61 Example System.out.print("1"); try { System.out.print("2"); if (true) throw new Exception(); System.out.print("3"); } catch (Exception e) { System.out.print("4"); } finally { System.out.print("5"); } System.out.println("6"); What does this print? What if we change new Exception() to new Throwable() ?

Chapter SeventeenModern Programming Languages62 Outline n 17.2 Throwable classes n 17.3 Catching exceptions n 17.4 Throwing exceptions n 17.5 Checked exceptions n 17.6 Error handling n 17.7 Finally n 17.8 Farewell to Java

Chapter SeventeenModern Programming Languages63 Parts We Skipped n Fundamentals – Primitive types: byte, short, long, float – Statements: do, for, break, continue, switch n Refinements – Inner classes: define classes in any scope: inside other classes, in blocks, in expressions – assert statement

Chapter SeventeenModern Programming Languages64 More Parts We Skipped n Packages – Classes are grouped into packages – In many Java systems, the source files in a directory correspond to a package – Default access (without public, private or protected ) is package-wide n Concurrency – Synchronization constructs for multiple threads – Parts of the API for creating threads

Chapter SeventeenModern Programming Languages65 More Parts We Skipped n The vast API n containers (stacks, queues, hash tables, etc.) n graphical user interfaces n 2D and 3D graphics n math n pattern matching with regular expressions n file IO n network IO and XML n encryption and security n remote method invocation n interfacing to databases and other tools