Program Errors Syntax errors Logic errors

Slides:



Advertisements
Similar presentations
Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
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.
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.
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.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
Java Programming Exceptions. Java has a built in mechanism for error handling and trapping errors Usually this means dealing with abnormal events or code.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
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.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
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.
Objectives Understanding what an exception is Understanding the heirarchy of exception classes Learn the types of exception and how to catch and handle.
 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 From Yesterday private = accessible only to the class that declares it public = accessible to any class at all protected = accessible to the class and.
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.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
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.
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.
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.
Chapter 9: Exceptions For error/problem situations Exception classes –ArithmeticException, IOException, etc. –checked exceptions try blocks –catch statements.
Question: What causes asynchronous control? Asynchronous control ≈ not determined by normal instruction execution Example int x = 2; // suppose a transfer.
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 }
Class Design: Handling Errors Reading: 2 nd Ed: Chapter 15 3 rd Ed: Chapter 11 Exercises 2 nd Ed: P15.5, P15.6 (Hint: look at documentation for Scanner.
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
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.
1 Exception handling in Java Reading for this lecture: Weiss, Section 2.5 (exception handling), p. 47. ProgramLive, chapter 10. I need to know whether.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
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.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
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.
Object Throwable ErrorException RuntimeException.
Chapter 10 – Exception Handling
Introduction to Exceptions in Java
Introduction to Exceptions in Java
Introduction to OO Program Design
Advanced Programming Behnam Hatami Fall 2017.
ATS Application Programming: Java Programming
Abdulmotaleb El Saddik University of Ottawa
Web Design & Development Lecture 7
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.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Chapter 12 Exception Handling and Text IO Part 1
Java Basics Exception Handling.
Presentation transcript:

Program Errors Syntax errors Logic errors Programming errors (faults) occur in two basic forms: Syntax errors A syntax error is a violation of the notational rules of the programming language. (synonym: compile-time errors) Logic errors A logic error results in potentially faulty behavior. Some logic errors are detected by the Java VM. The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

Run-time Errors Three Example Exceptions A detected error is generally called a run-time error. Java run-time errors produce exceptions. An exception is an abnormal condition that occurs during software execution. Three Example Exceptions String str = null; str = str.toLowerCase(); int j = 0; int k = 25/j; double[ ] arr = new double[3]; arr[3] = 29.4; When an exception occurs, it is said that “the exception is ”___________”. The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

Exception reports driley> java Driver Exception in thread "main" java.lang.NullPointerException at Driver.main(Driver.java:5) driley> String str = null; str = str.toLowerCase(); int j = 0; int k = 25 / j; double[ ] arr = new double[3]; arr[3] = 29.4; driley> java Driver Exception in thread "main" java.lang.ArithmeticException: / by zero at Driver.main(Driver.java:8) driley> driley> java Driver Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at Driver.main(Driver.java:11) driley> The Exception message includes the following information: • name of the method executing when the exception is thrown. • type of exception that occurred. • traceback of all active methods (and class(es), line number(s)).

Exception traceback Exception occurs in line of method in class driley> java Driver Exception in thread "main" java.lang.NullPointerException at Thing.doSomething(Thing.java:9) at Thing.<init>(Thing.java:5) at Driver2.main(Driver2.java:3) driley> doSomething called from line of constructor <init> Thing constructor called from line of method of class. The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

throw Instruction Example It is also possible to simulate an exception by executing a throw instruction. throw ExceptionObject; where ExceptionObject is an object reference conforming to Exception (Exception is a class from java.lang.) Example public class SimpleFraction { private int numerator, denominator; public SimpleFraction(int n, int d) { IllegalArgumentException error; if (d != 0) { numerator = n; denominator = d; } else { error = new IllegalArgumentException( “Fraction denominator of 0”); throw error; } public double realValue() { return (double)numerator / denominator; . . . public class runFractTest { public static void main(String[ ] args) { SimpleFraction myFrac; myFrac = new SimpleFraction(1, 2); System.out.println(myFrac.realValue()); myFrac = new SimpleFraction(1, 0); } The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

program executing normally Exception Flow program executing normally exception is thrown program is interrupted program terminates exception handler executes ??? The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

try Instruction try Syntax tryInstructionBody } catchClauses finallyClause catchClauses Syntax (zero or more repetitions of the following) catch (exceptionClassName parmName ) { exceptionHandlerBody } finallyClause Syntax (optional) finally { finallyBody } ...Body denotes a sequence of instructions. exceptionClassName - class conforming to Throwable. The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub. parmName - serves as a parameter passed into catch.

try Semantics Trace the following:  Execution of the try begins by executing the tryInstructionBody. Trace the following: System.out.println( “La Crosse” ); try { System.out.println( “River Falls” ); String str; System.out.println( str.trim() ); System.out.println( “Eau Claire” ); } catch ( NullPointerException e) { System.out.println( “Platteville” ); catch ( ArithmeticException e) { System.out.println( “Oshkosh” ); finally { System.out.println( “Whitewater” );  During the execution of tryInstructionBody the catchClauses serve as exception handlers. The appropriate catchClause is selected by conformance to a catchClauseName What if this line is deleted?  If a finallyClause is included, then it always executes after the try. The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

Details of Exception Handling Behavior When an exception is thrown execution proceeds as follows: 1)Normal instruction execution is suspended. 2)If the immediately enclosing try contains a matching catch, then the conforming catch clause serves as the exception handler. Otherwise, the current try body is aborted and the thrown exception is forwarded to the next instruction after the try. (If this is the last instruction in a method, then the exception is forwarded to the location of the call.) 3)Repeat Step 2 until an exception handler is located or all try instructions are exhausted. 4)The exception handler is executed, followed by finallyClause (if present). The remainder of the try instruction containing the catchClause is aborted and execution proceeds with the next instruction after the try. 5)If no matching catchClause is found, then this is considered to be an uncaught exception and the program terminates with a traceback. The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

Example Start trace by executing cud. public void cud() { try { System.out.println( "cud: before horn" ); horn(); System.out.println( "cud: after horn" ); udder(); System.out.println( "cud: after udder" ); } catch ( Exception e ) { System.out.println( "cud handler" ); public void horn() { System.out.println( "horn: before udder" ); System.out.println( "horn: after udder" ); System.out.println( "horn handler" ); public void udder() { System.out.println( ”udder: before exception" ); throw( new ArithmeticException() ); System.out.println( ”udder: after exception" ); Example Start trace by executing cud. The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

Exception Types Unchecked Exceptions Checked Exceptions All Java exceptions are represented by objects. (These objects are automatically passed as parameters to the exception handler.) Throwable «constructor» + Throwable() . . . «other» + String getMessage() + void printStackTrace() + String toString() The superclass of all exception objects is _________________. Exceptions partitioned into two categories. Unchecked Exceptions  are often severe, unpredictable.  may (or may not) be handled by a try instruction. Checked Exceptions  should be used for user-created exceptions.  must either be handled by a catch or included in a throws declaration. (throws explained later.) The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

Exception Types Classes from java.lang. Error subclasses (abridged) OutOfMemoryError StackOverflowError Unchecked Object Throwable Error Exception RuntimeException Checked Exception subclasses (abridged) IOException RuntimeException (abridged) ArithmeticException ClassCastException IllegalArgumentException IndexOutOfBoundsException NegativeArraySizeException NullPointerException SecurityException The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

Example . . . } catch ( NullPointerException e ) { try { . . . } catch ( NullPointerException e ) { System.out.println( ”null handler" ); catch ( IndexOutOfBoundsException e ) { System.out.println( ”index handler" ); catch ( OutOfMemoryError e ) { System.out.println( ”memory handler" ); catch (Exception e ) { System.out.println( e ); The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

throws When a method is called that can potentially throw a checked exception, then the code must do one of two things: 1) Be enclosed within a try instruction with a matching catch clause. 2) The surrounding method must include a throws suffix. OR Example public void cud() throws IOException { . . . } The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

Exceptions in Specifications Exceptions provide the opportunity to capture runtime errors. Such errors are best reported in method preconditions. Example /* pre: arr.length != 0 (throws ArithmeticException) * post: result = (summation of arr[0] through arr[arr.length-1]) / arr.length */ private double arrayAve(int[ ] arr) { int total == 0; for( int j = 0; j != arr.length; j++) { total = total + arr[j]; } return total / arr.length; The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.