Designing with Exceptions. CSE219, Computer Science III Stony Brook University http://www.cs.stonybrook.edu/~cse219



Similar documents
Software Construction

CS 111 Classes I 1. Software Organization View to this point:

What are exceptions? Bad things happen occasionally

Computing Concepts with Java Essentials

Lecture J - Exceptions

D06 PROGRAMMING with JAVA

Software Construction

I. INTRODUCTION. International Journal of Computer Science Trends and Technology (IJCST) Volume 3 Issue 2, Mar-Apr 2015

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Master of Sciences in Informatics Engineering Programming Paradigms 2005/2006. Final Examination. January 24 th, 2006

Java Application Developer Certificate Program Competencies

Approach of Unit testing with the help of JUnit

JAVA - EXCEPTIONS. An exception can occur for many different reasons, below given are some scenarios where exception occurs.

Software Engineering Techniques

CS506 Web Design and Development Solved Online Quiz No. 01

Testing, Debugging, and Verification

public static void main(string args[]) { System.out.println( "f(0)=" + f(0));

The Darwin Game 2.0 Programming Guide

Introduction to Programming System Design. CSCI 455x (4 Units)

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

For Introduction to Java Programming, 5E By Y. Daniel Liang

Java Programming Language

Course MS10975A Introduction to Programming. Length: 5 Days

Debugging Java Applications

Unit Testing. and. JUnit

Introduction to Java and Eclipse

Java Interview Questions and Answers

AP Computer Science Java Subset

Lab Experience 17. Programming Language Translation

Documentum Developer Program

Java from a C perspective. Plan

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

GDB Tutorial. A Walkthrough with Examples. CMSC Spring Last modified March 22, GDB Tutorial

Crash Course in Java

Agenda. What is and Why Polymorphism? Examples of Polymorphism in Java programs 3 forms of Polymorphism

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

How to test and debug an ASP.NET application

No no-argument constructor. No default constructor found

15-214: Principles of Software Construction 8 th March 2012

Explain the relationship between a class and an object. Which is general and which is specific?

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

#820 Computer Programming 1A

Lecture 1 Introduction to Android

Programming and Software Development (PSD)

Fundamentals of Java Programming

Chapter 1 Java Program Design and Development

JavaScript Testing. Beginner's Guide. Liang Yuxian Eugene. Test and debug JavaScript the easy way PUBLISHING MUMBAI BIRMINGHAM. k I I.

A Practical Method to Diagnose Memory Leaks in Java Application Alan Yu

Effective unit testing with JUnit

language 1 (source) compiler language 2 (target) Figure 1: Compiling a program

Mail User Agent Project

Unit Testing JUnit and Clover

Getting Started with the Internet Communications Engine

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Service Integration course. Cassandra

Exception Handling In Web Development DevelopIntelligence LLC

UI Performance Monitoring

Introduction to Eclipse

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

Using Files as Input/Output in Java 5.0 Applications

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

VB.NET Programming Fundamentals

Java SE 8 Programming

public static void main(string[] args) { System.out.println("hello, world"); } }

Building Java Programs

TESTING WITH JUNIT. Lab 3 : Testing

Announcement. SOFT1902 Software Development Tools. Today s Lecture. Version Control. Multiple iterations. What is Version Control

COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms.

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Introduction to Data Structures

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Java Basics: Data Types, Variables, and Loops

Specialized Programme on Web Application Development using Open Source Tools

Creating a Simple, Multithreaded Chat System with Java

Chapter 1: Key Concepts of Programming and Software Engineering

Mobile Application Development Android

Common Beginner C++ Programming Mistakes

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

Coding in Industry. David Berry Director of Engineering Qualcomm Cambridge Ltd

Monitoring, Tracing, Debugging (Under Construction)

Reshaping & Combining Tables Unit of analysis Combining. Assignment 4. Assignment 4 continued PHPM 672/677 2/21/2016. Kum 1

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

Monitis Project Proposals for AUA. September 2014, Yerevan, Armenia

Figure 1: Graphical example of a mergesort 1.

Lecture 9. Semantic Analysis Scoping and Symbol Table

Moving from CS 61A Scheme to CS 61B Java

JCrasher: an automatic robustness tester for Java

Debugging Multi-threaded Applications in Windows

This section provides a 'Quickstart' guide to using TestDriven.NET any version of Microsoft Visual Studio.NET

Introduction to Java

CS 106 Introduction to Computer Science I

Developing In Eclipse, with ADT

Core Java+ J2EE+Struts+Hibernate+Spring

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Time Limit: X Flags: -std=gnu99 -w -O2 -fomitframe-pointer. Time Limit: X. Flags: -std=c++0x -w -O2 -fomit-frame-pointer - lm

Programmation 2. Introduction à la programmation Java

Transcription:

Designing with Exceptions CSE219, Computer Science III Stony Brook University http://www.cs.stonybrook.edu/~cse219

Testing vs. Debugging Testing Coding Does the code work properly YES NO 2 Debugging

Testing Tells us when something is wrong not how to fix it 3

Debugging Process of understanding and correcting errors First locate the problem find line of your code that produces initial problem Then address the algorithm change/modify/correct 4

Debugging is an important skill Become proficient ASAP why? Reveal bugs that are not otherwise evident like infinite loops Don t design to debug Don t rely on debugging to write code define and implement correct algorithms fast debugging << correct implementation 5

Debugging Strategy When you know a bug exists for a particular case Determine in which class the error originates Determine in which method the error originates Determine on which line of code the error originates Knowing where the problem originates is half the battle Reproducing an error helps 6

Common Bugs Revealed by Debugging Unconstructed Objects Uninitialized Variables Failing to reinitialize a variable in loop Improper Iteration Missing Implementations Incomplete Changes 7

Not all errors are created equal On difficulty scale: syntax errors << runtime errors << logical errors Note: runtime errors may be due to logical errors 8

Plan to Debugging Assumption: Murphy s Law reigns supreme If there can be a bug, there (most probably) IS a bug! So? Design, write, & document your programs in ways that will make them easier to test & debug How? write well-documented modular code avoid I'll fix this later approach 9

Professionals use tools Even for tracking bugs (e.g., Bugzilla) 10

Debugging by Brute Force I.e. the print statement display contents of select variables display benchmarks of program progress i.e. Is this line of code reached? System.out.println( Before Foo ); foo(); System.out.println( After Foo ); Advantage: 11 easy to implement

Disadvantages of print Approach Makes a mess of code Hit-or-miss Can't identify certain types of problems Not easy to use for: Large-scale programs Graphical programs Web apps Mobile apps 12

Debugging by Brute Force Example private static boolean debug = true;... public int calculate (int y, int z) { int x; x = mystery(y); if (debug) { System.out.println( DEBUG: x = + x + y = + y); } x += mystery(z); return x; } 13

Debugging by IDE All modern IDEs provide: examination of the contents of variables setting and removing of breakpoints query and search commands single-step execution through a program examination of different threads of execution 14

NetBeans Debugger Similar to other IDE debuggers eclipse, Visual Studio, etc. Set Breakpoints place where debugger will stop Walk through code via: Stop Pause Continue Step Over Step Over Expression Step Into 15 Step Out

Robust Programs Methods have domain (arguments) & range (results) Total methods behavior is defined for all inputs in the method domain By definition these are robust methods Partial methods can lead to programs that are not robust they may not behave reasonably on arguments that it can t handle if an error occurs, robust programs behave in a well-defined error handling system. Graceful degradation providing some approximation of its behavior Halt with a meaningful error message without crashing or otherwise causing damage 16

Exceptions 17 Allow the flow of control to move from the location of an error to an error handler Better than returning -1? Treats errors differently from normal results Forces the programmer to deal with these errors Types of errors: User input errors Device errors Physical limitations Code errors An exception is an abstraction allows us to handle errors in a more general way

Exceptions/Errors in Java Exceptions can be checked or unchecked Checked exceptions subclasses of java.lang.exception except java.lang.exception.runtimeexception and its subclasses the Java compiler forces you to either catch checked exceptions, or declare them in the method signature Unchecked exceptions java.lang.runtimeexception and its subclasses java.lang.error and its subclasses compiler doesn t know about these: NullPointerException, OutOfMemoryError 18

Exceptions in Java Throwable Error Exception Unchecked Exceptions RuntimeException Unchecked Exceptions Checked Exceptions public void filereadermethod() throws IOException {...} checked exception have to either use a try-catch block or throw it explicitly public void anothermethod() {... } May throw an unchecked exception No need to catch or throw it (but you may choose to do so) 19

Handling Exceptions An exception is handled in two ways: Enclose the method call that can cause an exception in a try block. Use a catch block to handle the possible exception. Pass the exception back to the current method s caller. Java automatically passes the exception to the method s caller if: the exception type of one of its supertypes is listed in the method s header (in a throws clause) the exception type is unchecked Again! Make sure that any exception your code raises is listed in the header and is described in the method s specification. 20

Tips on Using Exceptions 21 Too much exception handling will slow your code down dramatically. Exception handling is not supposed to replace a simple test by an application. Robust GUIs should check input from users before processing information. Exceptions serve to protect the methods & classes that throw them, Defensive programming: writing each procedure to defend itself against errors.

Tips on Using Exceptions Do not micromanage exceptions Example: Read a string and convert it to an int try { line = infile.readline(); } catch (IOException e) { System.out.println(e); } try { num = Integer.parseInt(line); } catch (NumberFormatException e) { System.out.println(e); } Put both exceptions into a single catch! 22

Tips on Using Exceptions Continue example: try { line = infile.readline(); num = Integer.parseInt(line); } catch (IOException e) { System.out.println(e); } catch (NumberFormatException e) { System.out.println(e); } 23 And separate normal processing from error handling.

Tips on Using Exceptions Do not squelch/suppress/ignore exceptions. Example: Popping off a stack with 100 elements. sum = 0; for (i=1; i <= 100; i++){ try { sum += s.pop(); }catch(emptystackexception e){ } // squelched! } Logical errors can be completely missed if exceptions are ignored! 24

Reflecting is Good Method A calls method B, which throws an exception, rather than passing the exception: The caller A explicitly catches the exception from B and throws a different type of exception. Example: Find the min of an array. Method begins by trying to get the element in position 0. If the array is empty, IndexOutOfBoundsException is thrown. The min method may catch this and return EmptyArrayException. Why would we want to do this? Turn vague exceptions into more relevant ones! Turn unchecked exceptions into checked ones! 25

public static int min(int[] a) throws EmptyArrayException { } try{ int min = a[0]; }catch(indexoutofboundsexception e) } throw new EmptyArrayException(); 26

Masking Method A calls method B, which throws an exception. The caller A explicitly catches and handles the exception and continues with the normal flow Any method calling A is none the wiser Example: Sorting an array. Method tries to get element in position 0. If the array is empty, the array is already sorted (by definition). Method catches IndexOutOfBoundsException and masks it. 27

Design Issues with Exceptions When should one use them? Checked or unchecked? Use existing Exception classes or make your own? 28

When Do We Use Exceptions? Exceptions should be used to prevent data (static or instance variables) from reaching an illegal state Make a partial method more like a total method Exceptions may be avoided (by returning an int error code) if a method is used only locally Ex: private helper methods Use exceptions for exceptional situations Special Java rule for overriding: If you override a method, the subclass method cannot throw more checked exceptions than the superclass that you replace. 29

Use checked or unchecked? 30 Always use checked exceptions! Why? let other programmers (and yourself) be aware of potential errors make them anticipate these errors make them handle these errors as they see fit Many exceptions in the JDK are unchecked. Why? It would clutter the code (example: having a try block for every indexed array, division or object use).

Programmer vs. User Unchecked exceptions occurring are generally the fault of the programmer Checked exceptions occurring may be the fault of the user/system/internet access 31

Testing and debugging in large projects Testing using frameworks: 32 JUnit Unit testing framework for the Java programming language Testing individual components Used in regression testing import org.junit.*; TestSuite suite= new TestSuite(); suite.addtest( new Test( )) Apache Log4J Logging results of applications Also used in debugging Web applications Properties stored in property file log4j.properties: log = /usr/home/log4j log4j.rootlogger = DEBUG, FILE Use: import org.apache.log4j.logger; static Logger log = Logger.getLogger( log4jexample.class.getname()); log.debug("this is an debug message");