• No results found

Software Construction

N/A
N/A
Protected

Academic year: 2021

Share "Software Construction"

Copied!
14
0
0

Loading.... (view fulltext now)

Full text

(1)

Software Construction

Debugging and Exceptions

Jürg Luthiger

University of Applied Sciences Northwestern Switzerland Institute for Mobile and Distributed Systems

Learning Target

You

ƒ

know the proper usage of exceptions

ƒ

know how to use the assert keyword

(2)

Institut für Mobile und Verteilte Systeme J. Luthiger 3

Agenda

ƒ

Introduction into Exceptions

ƒ

Introduction into Assert

ƒ

Using the Eclipse Debugger

The nature of Exceptions

ƒ

Exceptions

‹ due to programming errors

z e.g. NullPointerException, IllegalArgumentException

‹ due to client code errors

z wrong usage of the API

‹ due to resource failures

z out of memory

(3)

Institut für Mobile und Verteilte Systeme J. Luthiger 5

Pitfalls

ƒ

If not used correctly, exceptions can slow down

the program, as it takes CPU power to create, throw and catch exceptions

ƒ

If overused, exceptions make the code difficult

to read and are frustrating for programmers to use the API

The Problem using Exceptions

public void consumeAndForgetAllExceptions() { try {

… some code that throws exceptions } catch (Exception e) {

ex.printStackTrace(); }

}

public void someMethod() throws Exception { }

How can a blank method throw an exception?

Execution of the program continues after the catch block, as if nothing had happened

(4)

Institut für Mobile und Verteilte Systeme J. Luthiger 7

Compiler Error vs. Runtime Errors

ƒ

Compiler errors are generated by the compiler.

They are developer friendly!

ƒ

Runtime errors are generated by the runtime

system-> Program crash if exceptions are not handled correctly , not at all user friendly

ƒ

The handling of the exceptions is

developer-intensive

Exception Types in Java

ƒ

java.lang.RuntimeException

=> UNCHECKED no compiler checks

ƒ

java.lang.Exception

=> CHECKED

Compiler checks, if there exist an Exception Handling

(5)

Institut für Mobile und Verteilte Systeme J. Luthiger 9

Sample Exception Hierarchy

Exception

RuntimeException SQLException

NullPointerException

Misuse of Checked Exceptions

ƒ

Checked Exceptions are a forced contract on

the invoking layer to catch or to throw it.

ƒ

Unwanted burden of the client code is unable to

deal with the exception effectively ‹ using empty catch block

‹ just throwing it and placing burden on the invoker

ƒ

Breaking encapsulation

public List getAllAccounts() throws

(6)

Institut für Mobile und Verteilte Systeme J. Luthiger 11

Best Practices: 1

When deciding on checked exceptions vs. unchecked exceptions, ask yourself, "What action can the client code take when the exception occurs?"

If the client can take alternate action to recover from the exception, make it a checked exception. If the client cannot do anything useful, then make the exception unchecked.

Best Practices: 2

Preserve encapsulation

For example, do not propagate SQLException

from the database to the application layer. Convert them into unchecked exceptions:

try {

...some code that throws SQLException } catch (SQLException e) {

throw new RuntimeException(ex); }

(7)

Institut für Mobile und Verteilte Systeme J. Luthiger 13

Best Practices: 3

Try not to create new custom exceptions if they do not have useful information for client code.

public class DuplicateUsernameException extends Exception {}

public class DuplicateUsernameException extends Exception { public DuplicateUsernameException (String username){....} public String requestedUsername(){...}

public String[] availableNames(){...} }

should be better

throw new RuntimeException("Username already taken");

or even simpler

Best Practices: 4

Document Exceptions

ƒ

Use Javadoc @throws tag

ƒ

Write Unit test

@Test(expected = IndexOutOfBoundsException.class)

public void testIndexOutOfBoundsException() { ArrayList blankList = new ArrayList(); blankList.get(10);

(8)

Institut für Mobile und Verteilte Systeme J. Luthiger 15

Using Exceptions: 1

Always clean up after yourself

ƒ

Resources like database or network

connections should always be closed

public void dataAccessCode(){ Connection conn = null; try {

conn = getConnection();

..some code that throws SQLException } catch(SQLException ex){ ex.printStacktrace(); } finally{ DBUtil.closeConnection(conn); } }

Using Exceptions: 2

Never use exceptions for flow control

public void useExceptionsForFlowControl() { try {

while (true) {

increaseCount(); }

} catch (MaximumCountReachedException ex) { }

//Continue execution }

public void increaseCount()

throws MaximumCountReachedException { if (count >= 5000)

(9)

Institut für Mobile und Verteilte Systeme J. Luthiger 17

Using Exceptions: 3

Do not suppress or ignore exceptions

ƒ

When a method from an API throws a checked

exception, it is trying to tell you that you should take some counter action.

ƒ

If the checked exception does not make sense

to you, do not hesitate to convert it into an unchecked exception and throw it again.

Using Exceptions: 4

Do not catch top-level exceptions

ƒ Unchecked exceptions inherit from the

RuntimeException class, which in turn inherits from Exception.

ƒ By catching the Exception class, you are also catching RuntimeException as in the following code:

try{ ..

} catch(Exception ex) { }

(10)

Institut für Mobile und Verteilte Systeme J. Luthiger 19

Using Exceptions: 5

Log exceptions just once

ƒ

Logging the same exception stack trace more

than once can confuse the programmer

examining the stack trace about the original source of exception. So just log it once.

Summary Guidelines

1.

The caller MUST handle the exception =>

CHECKED

2.

A Minority will handle the exception =>

UNCHECKED

3.

Is a runtime error irresolvable =>

UNCHECKED

(11)

Institut für Mobile und Verteilte Systeme J. Luthiger 21

Exception chaining

ƒ

Exception chaining means that the constructor

of an exception object takes a ‘nested’ or ‘cause’ exception as an argument.

ƒ

The newly created higher level exception object

will then maintain a reference to the underlying root cause exception.

...

} catch (FileNotFoundException e) {

throw new MyException("Additional Comments", e);

}

How to write Exceptions...

public class MyException extends Exception { public MyException(String message) {

super(message); }

public MyException(String message, Throwable t) { super(message, t);

} }

IMPORTANT: Decide when to use CHECKED or UNCHECKED Exception!

(12)

Institut für Mobile und Verteilte Systeme J. Luthiger 23

Still to remember...

ƒ

Checked Exception are MUCH, MUCH better

than every error code, as seen in languages like C and C++ (!)

Asserts

ƒ

You can use assertions to detect errors that

may otherwise go unnoticed.

ƒ

Assertions contain Boolean expressions that

define the correct state of your program at specific points in the program source code.

ƒ

The Java SE platform 1.4, has introduced a

(13)

Institut für Mobile und Verteilte Systeme J. Luthiger 25

Design by contract

ƒ Precondition: A condition that the caller of an operation agrees to satisfy

‹ The user invoking the computation has the responsibility of

providing the correct input, which is a precondition. ƒ Postcondition: A condition that the method itself

promises to achieve

‹ If the computation is successful, we say that the computation

has satisfied the postcondition.

ƒ Invariant: A condition that a class must satisfy anytime a client could invoke an object's method, or a condition that should always be true for a specified segment or at a specified point of a program

Using Assertions

ƒ

Use the assert statement to insert assertions at

particular points in the code.

assert booleanExpression;

(14)

Institut für Mobile und Verteilte Systeme J. Luthiger 27

Debugger

ƒ

see

"Using the Eclipse Debugger"

"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to

debug it."

References

Related documents

The All Tribes calls provide an opportunity for CMS to solicit input from IHS, Tribal, and urban programs on how implementation of or changes to CMS legislative and

Rule 1.2 authorizes a lawyer to "take such action on behalf of the client as is impliedly authorized to carry out the representation...." In addition, subsection (b) of

• 30mm Aperture Slot - large enough to receive bulky mail though small enough to provide mail security.. • 30mm Weatherhood provides mail security and weather

FACTS: The claim was presented for damage to the claimant’s vehicle that resulted when the claimant struck a parked and unoccupied City vehicle. POSSIBLE

⇒ Copy mode screen X [Basic] X [Feed tray] X select the standard tray X [Change] X [Paper type] X [Feed ctrl.].. Problem Possible Cause and Action

Creative Pro Qualifying Revenue is defined as the value to Adobe of purchases, less any returns, effected by Distributor (“sellthrough value”) directly from Adobe, of all

As well as the many on-going services the Customer Loyalty Team can provide, there is a vast array of additional resources that can help you get more from your software, plus give

A postal survey of British and South Korean shippers was conducted to analyse the operation of the logistics service in the liner shipping industry. The selected sampling method was