Designing with Exceptions. CSE219, Computer Science III Stony Brook University

Similar documents
Designing with Exceptions. CSE219, Computer Science III Stony Brook University

Computing Concepts with Java Essentials

What are exceptions? Bad things happen occasionally

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

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

Software Engineering Techniques

Software Construction

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

Lecture J - Exceptions

Debugging Java Applications

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

D06 PROGRAMMING with JAVA

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

Approach of Unit testing with the help of JUnit

CS506 Web Design and Development Solved Online Quiz No. 01

Lab Experience 17. Programming Language Translation

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

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

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

Introduction to Java and Eclipse

How to test and debug an ASP.NET application

The Darwin Game 2.0 Programming Guide

Course MS10975A Introduction to Programming. Length: 5 Days

Testing, Debugging, and Verification

Java Interview Questions and Answers

Documentum Developer Program

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

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

Crash Course in Java

Instrumentation Software Profiling

Exception Handling In Web Development DevelopIntelligence LLC

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

Java Application Developer Certificate Program Competencies

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

Programming and Software Development (PSD)

Performance Improvement In Java Application

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

Debugging Multi-threaded Applications in Windows

Java SE 8 Programming

Mail User Agent Project

#820 Computer Programming 1A

Unit Testing JUnit and Clover

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

Lecture 1 Introduction to Android

Unit Testing. and. JUnit

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

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

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

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

Monitoring, Tracing, Debugging (Under Construction)

MS Enterprise Library 5.0 (Logging Application Block)

Core Java+ J2EE+Struts+Hibernate+Spring

Volta Log Library user manual

Fundamentals of Java Programming

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

Effective unit testing with JUnit

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

Eclipse installation, configuration and operation

Java Troubleshooting and Performance

What Is Specific in Load Testing?

Specialized Programme on Web Application Development using Open Source Tools

Chapter 1 Java Program Design and Development

Service Integration course. Cassandra

Lecture 9. Semantic Analysis Scoping and Symbol Table

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

Mobile Application Development Android

Figure 1: Graphical example of a mergesort 1.

Introduction to Eclipse

3D Animation of Java Program Execution for Teaching Object Oriented Concepts

Change Impact Analysis

Chapter 12 Programming Concepts and Languages

Integrated Error-Detection Techniques: Find More Bugs in Java Applications

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

Lecture 11: Tail Recursion; Continuations

Research Data Management CODING

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Computer Programming I

Monitoring of Tritium release at PTC.

No no-argument constructor. No default constructor found

Database Programming with PL/SQL: Learning Objectives

Visual Basic. murach's TRAINING & REFERENCE

Programming in C# with Microsoft Visual Studio 2010

TESTING WITH JUNIT. Lab 3 : Testing

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Chronon: A modern alternative to Log Files

Introduction to Data Structures

Using Files as Input/Output in Java 5.0 Applications

Introduction to Java

Chapter 1: Key Concepts of Programming and Software Engineering

Chapter 5 Names, Bindings, Type Checking, and Scopes

UI Performance Monitoring

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

<Insert Picture Here> What's New in NetBeans IDE 7.2

Generating Automated Test Scripts for AltioLive using QF Test

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

Getting Started with the Internet Communications Engine

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

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 correct implementation of algorithm OR change algorithm 4

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

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 Un-constructed Objects Un-initialized 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: every program will contain faults no programmer gets it right the first time So? Design, write, & document your programs in ways that will make them easier to test & debug 9 How? write well-documented modular code avoid I'll fix this later approach

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. 15 Set Breakpoints place where debugger will stop Walk through code via: Stop Pause Continue Step Over Step Over Expression Step Into Step Out

Robust Programs 16 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 Robust program continues to behave reasonably even in the presence of errors If an error occurs, robust programs behave in a well-defined way. Either: Providing some approximation of its behavior in the absence of an error = graceful degradation OR Halt with a meaningful error message without crashing or damage to permanent data or software systems

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 An exception may be thrown because: A method is called that throws a checked exception. FileNotFoundException, IOException A method is called that detects an error and explicitly throws a checked exception. Create your own class that extends Exception. A method throws an unchecked exception due to a programming error (i.e. a run-time logical error). ArithmeticException,NullPointerException An internal error occurs in the Java Virtual Machine (JVM) or runtime library. e.g. VirtualMachineError, OutOfMemoryError 18

Method Design w/ Exceptions 19 Throw an exception when a method s preconditions are not met As well as any other error condition found in the method Throw different types of exceptions for different types of problems Specify detailed information about the reason for the exception in the Exception message Provide a specification of all exceptions possibly thrown inside a method

Exceptions in Java Throwable Error Exception RuntimeException Checked Exceptions 20 Unchecked Exceptions A method throwing a checked exception must declare the exception in the header via throws A method throwing an unchecked exception does not have to declare the exception in its header but it is advisable to do so! also, make sure your specification explains the conditions that generate each exception

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. 21

Tips on Using Exceptions 22 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! 23

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); } 24 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! 25

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! 26

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

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. 28

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

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. 30

Use checked or unchecked? 31 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 32

Testing and debugging in large projects Testing using frameworks: JUnit 33 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");