17. 1. Representation
• 程式語言表達例外的方法
– Symbol
• strings or numbers
– Data object
• Used to hold error and failure information only.
• Raised by a language keyword.
– Full object
• Encapsulate signaling, propagation, and continuation
behaviors of exceptions in the class definition.
Copyright@2013 Teddysoft
18. 2. Definition
• 程式設計師如何定義一個例外
– Symbols
• new exceptions are defined as strings or
numbers.
– Data objects and full objects
• a class is used to define an exception.
Copyright@2013 Teddysoft
19. 3. Signaling
• 產生一個例外(的實例),並且將例外傳給
接收者的指令稱之為:
– throwing, signaling, raising, or triggering
• 例外產生方式有兩種:
– Synchronous exception
• A direct result of performing the instruction.
– Asynchronous exception
• Produced by the runtime environment upon encountering
an internal error or by stopping or suspending a thread.
Copyright@2013 Teddysoft
20. 4. Propagation
• If an exception is signaled and not coped
with locally, the exception can be propagated
to the caller of the signaling method.
• Exception propagation can be explicit or
implicit (or automatic).
– Explicit: a receiver must explicitly re-throw an
unhandled received exception for further propagation
– Implicit: an unhandled exception is automatically
propagated.
Copyright@2013 Teddysoft
21. 5. Resolution
• Exception resolution or handler binding is a process
of finding a suitable handler in the target, which is
resolved by static scoping at compiler-time, dynamic
invocation chain at runtime, or both.
• There are two methods to dynamically find a handler:
stack unwinding and stack cutting.
– Stack unwinding pops the stack frames to search for the
matching exception handler
– Stack cutting maintains a list of registered exception handlers
and looks up the list for a suitable exception handler.
Copyright@2013 Teddysoft
22. 6. Continuation
• An exception continuation or exception
model specifies the execution flow after
an exception handler returns its control.
– Termination model
– Retry model
– Resumption model
Copyright@2013 Teddysoft
23. 容易搞混且重要的觀念:Fault, Error,
Failure, Exception彼此的關係
cause of failure
fault
(1) design
(2) component
a state may lead to
failure
error
service departs from
specification
failure
represented by
exception
Copyright@2013 Teddysoft
46. Declared Exception
public void fetchRawBytesAndSetupMessage(DataInputStream aIS)
throws IOException, InvalidPacketException {
int length = aIS.readInt();
setMessageLength(length);
byte[] messageBody = new byte[length];
try {
aIS.readFully(messageBody);
} catch (EOFException e) {
throw new InvalidPacketException("Data Underflow");
}
setMessage(new String(messageBody));
}
Copyright@2013 Teddysoft
47. Undeclared Exception
(1/2)
public Hamburg createHamburger(String type) {
Hamburg ham = null;
}
switch (type) {
case "pork":
ham = new SweetPorkHamburger();
break;
case "beef":
ham = new SweetBeefHamburger();
break;
default:
throw new RuntimeException
("Unsupported hamburger type:" +
type);
}
return ham; Copyright@2013 Teddysoft
48. Undeclared Exception
(2/2)
public void deposit(int value) {
if (value < 0 ) {
throw new IllegalArgumentException
("存款金額不得為負數.");
}
// doing normal deposit logic
}
Copyright@2013 Teddysoft
49. 你在做例外處理還是容錯設計?
public void deposit(int value) {
if (value < 0 ) {
throw new IllegalArgumentException
("存款金額不得為負數.");
}
UC
UD
// doing normal deposit logic
}
public void deposit(int value) throws
llegalArgumentException {
if (value < 0 ) {
D
throw new IllegalArgumentException
("存款金額不得為負數.");
UC
}
// doing normal deposit logic
}
Copyright@2013 Teddysoft
(1/2)
61. 不同的程式語言有不同的例外處理構件
• Java/C#
– try-catch-finally
• C++
– try-catch
– destructor
• Eiffel
– Exception handlers in Eiffel are attached at the method
level and all exceptions are caught by one handler.
61
Copyright@2013 Teddysoft
62. 重新思考try-catch-finally的責任與分工
• Try
– Implement requirements (can have alternatives)
– Prepare state recovery (e.g., make a check point)
• Catch
– Perform error and fault handling
– Report exceptional conditions
– Control retry flow
• Finally
– Release resources
– Drop check points if any
62
Copyright@2013 Teddysoft
71. Process View
• Waterfall VS. IID (iterative and
incremental development)
• 如何在IID流程中規劃例外處理?
– I will handle this exception when I have time.
Never happens!
Copyright@2013 Teddysoft
72. 以Scrum為例
• Story
– Normal scenarios
– Failure scenarios
• 這個sprint先做normal scenarios,下個
sprint再做failure scenarios
敏捷開發讓例外處理變得好簡單啊!
Copyright@2013 Teddysoft
才怪
80. Robustness Levels (強健度等級)
3
BehaviorRecovery
Service is delivered under the
presence of exceptions
2
State is correct under the
presence of exceptions
1
All exceptions are
reported
StateRecovery
ErrorReporting
Undefined
0
Robustness
unpredictable
80
Copyright@2013 Teddysoft
81. Robustness levels of components
Element
RL G0
RL G1
RL G2
RL G3
name
undefined
error-reporting
state-recovery
behavior-recovery
service
failing implicitly or
explicitly
failing explicitly
failing explicitly
delivered
state
unknown or incorrect
unknown or
incorrect
correct
correct
lifetime
terminated or
continued
terminated
continued
continued
NA
(1) propagating all
unhandled
(1) error
exceptions, and
recovery
(2) catching and
and
reporting them in
(2) cleanup
the main program
howachieved
also known
NA
as
failing-fast
Copyright@2013 Teddysoft
weakly tolerant
and organized
panic
(1) retry, and/or
(2) design
diversity, data
diversity, and
functional diversity
strongly tolerant,
self-repair, selfhealing, resilience,
and retry
82. Upgrading and degrading
exception handling goals
restore state, clean up,
and keep programs alive
attempt retries
fail-fast; keep
user informed
G0
G1
G2
state restoration
or cleanup fail
G3
all retries fail
82
Copyright@2013 Teddysoft
83. Applicability for the robustness levels
RL
Applicability
In the early stage of system development
Prototyping
G1
Applying an evolutionary development methodology
Time-to-market
Outsourcing
G2 Designing utility components used in different application domains
Behavior-recovery actions should be administered by the user
Developing mission critical systems
Designing components having sufficient application context to
G3
recover from behavioral failures, e.g., application controllers
Behavior-recovery actions are inappropriate to be administered by
the user
83
Copyright@2013 Teddysoft
88. What is Refactoring
• Improving the internal structure of a
software system without altering its
external behavior [fowler]
• Steps to perform refactoring:
– Identifying code smells
– Applying refactorings to remove the smells
– Verifying satisfaction
Copyright@2013 Teddysoft
89. Refactoring and EH Refactoring
Refactoring
Normal
Behavior
EH Refactoring
Exceptional
Behavior
Behavior
89
Copyright@2013 Teddysoft
90. EH Smells, Refactorings, and RL
EH smell
Return code
Ignored checked
exception
Unprotected main
program
Dummy handler
Nested try block
Refactoring
Replace Error Code with Exception
Replace Ignored Checked Exception with
Unchecked Exception
Avoid Unexpected Termination with Big
Outer Try Block
Replace Dummy Handler with Rethrow
Replace Nested Try Block with Method
Replace Careless Cleanup with Guaranteed
Careless Cleanup
Cleanup
Ignored checked
exception
Introduce Checkpoint Class
Dummy handler
Spare handler
Introduce Resourceful Try Clause
Copyright@2013 Teddysoft
RL
G1
G1
G1
G1
G2
G2
G2
G3
90
91. Smell: Return Code
public int withdraw(int amount) {
if (amount > this.balance)
return -1;
else {
this.balance = this.balance – amount;
return this.balance;
}
}
91
Copyright@2013 Teddysoft
92. Refactoring: Replace Error Code with
Exception
public int withdraw(int amount) throws
NotEnoughMoneyException {
if (amount > this.balance)
throw new NotEnoughMoneyException ();
this.balance = this.balance – amount;
}
92
Copyright@2013 Teddysoft
93. Smell: Ignored Checked Exception
public void writeFile(String fileName, String data) {
Writer writer = null;
try {
writer = new FileWriter(fileName);
// may throw IOException
writer.write(data); // may throw IOException
}
catch (IOException e) { // ignoring the exception }
finally { // code for cleanup }
}
93
Copyright@2013 Teddysoft
94. Replace Ignored Checked Exception
with Unchecked Exception
public void writeFile(String fileName, String data) {
Writer writer = null;
try {
writer = new FileWriter(fileName); /* may throw an IOException */
writer.write(data); /* may throw an IOException */
}
catch (IOException e) {
/* ignoring the exception */
}
}
↓
public void writeFile(String fileName, String data) {
Writer writer = null;
try {
writer = new FileWriter(fileName); /* may throw an IOException */
writer.write(data); /* may throw an IOException */
}
catch (IOException e) {
throw new UnhandledException(e, “message”);
}
}
Copyright@2013 Teddysoft
94
95. Smell: Unprotected Main Program
static public void main(String[] args) {
MyApp myapp = new MyApp();
myapp.start();
}
95
Copyright@2013 Teddysoft
96. Avoid Unexpected Termination with
Big Outer Try Block
static public void main(String[] args) {
MyApp myapp = new MyApp();
myapp.start();
}
↓
static public void main(String[] args) {
try {
MyApp myapp = new MyApp();
myapp.start();
}
catch (Throwable e) {
/* displaying and/or logging the exception */
}
}
Copyright@2013 Teddysoft
96
106. Introduce Checkpoint Class
public void foo () throws FailureException {
try {
/* code that may change the state of the object */
}
catch (AnException e) {
throw new FailureException(e);
} finally {/* code for cleanup */}
}
↓
public void foo () throws FailureException {
Checkpoint cp = new Checkpoint (/* parameters */);
try {
cp. establish (); /* establish a checkpoint */
/* code that may change the state of the object */ }
catch (AnException e) {
cp.restore (); /* restore the checkpoint */
throw new FailureException(e); }
finally { cp.drop(); }
}
Copyright@2013 Teddysoft
106