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彼此的關係
fault error failure
exception
(1) design
(2) component
cause of failure a state may lead to
failure
service departs from
specification
represented by
Copyright@2013 Teddysoft
46. Declared Exception
Copyright@2013 Teddysoft
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));
}
47. Undeclared Exception (1/2)
Copyright@2013 Teddysoft
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;
}
48. Undeclared Exception (2/2)
Copyright@2013 Teddysoft
public void deposit(int value) {
if (value < 0 ) {
throw new IllegalArgumentException
("存款金額不得為負數.");
}
// doing normal deposit logic
}
49. 你在做例外處理還是容錯設計? (1/2)
Copyright@2013 Teddysoft
public void deposit(int value) throws
llegalArgumentException {
if (value < 0 ) {
throw new IllegalArgumentException
("存款金額不得為負數.");
}
// doing normal deposit logic
}
public void deposit(int value) {
if (value < 0 ) {
throw new IllegalArgumentException
("存款金額不得為負數.");
}
// doing normal deposit logic
}
D
UC
UCUD
50. 你在做例外處理還是容錯設計? (2/2)
public String execute(String cmd) throws
IOException,
NullPointerException,
IllegalArgumentException;
Copyright@2013 Teddysoft
UCD
CD
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
敏捷開發讓例外處理變得好簡單啊! 才怪
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
how-
achieved
NA
(1) propagating all
unhandled
exceptions, and
(2) catching and
reporting them in
the main program
(1) error
recovery
and
(2) cleanup
(1) retry, and/or
(2) design
diversity, data
diversity, and
functional diversity
also known
as
NA failing-fast
weakly tolerant
and organized
panic
strongly tolerant,
self-repair, self-
healing, resilience,
and retry
Copyright@2013 Teddysoft
82. Upgrading and degrading
exception handling goals
82
fail-fast; keep
user informed
G0 G1 G2
restore state, clean up,
and keep programs alive
G3
attempt retries
all retries fail
state restoration
or cleanup fail
Copyright@2013 Teddysoft
83. Applicability for the robustness levels
83
RL Applicability
G1
In the early stage of system development
Prototyping
Applying an evolutionary development methodology
Time-to-market
G2
Outsourcing
Designing utility components used in different application domains
Behavior-recovery actions should be administered by the user
G3
Developing mission critical systems
Designing components having sufficient application context to
recover from behavioral failures, e.g., application controllers
Behavior-recovery actions are inappropriate to be administered by
the user
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
89
Normal
Behavior
Exceptional
Behavior
Refactoring EH Refactoring
Behavior
Copyright@2013 Teddysoft
90. EH Smells, Refactorings, and RL
90
EH smell Refactoring RL
Return code Replace Error Code with Exception G1
Ignored checked
exception
Replace Ignored Checked Exception with
Unchecked Exception
G1
Unprotected main
program
Avoid Unexpected Termination with Big
Outer Try Block
G1
Dummy handler Replace Dummy Handler with Rethrow G1
Nested try block Replace Nested Try Block with Method G2
Careless Cleanup
Replace Careless Cleanup with Guaranteed
Cleanup
G2
Ignored checked
exception
Dummy handler
Introduce Checkpoint Class G2
Spare handler Introduce Resourceful Try Clause G3Copyright@2013 Teddysoft
91. Smell: Return Code
91
Copyright@2013 Teddysoft
public int withdraw(int amount) {
if (amount > this.balance)
return -1;
else {
this.balance = this.balance – amount;
return this.balance;
}
}
92. Refactoring: Replace Error Code with
Exception
92
Copyright@2013 Teddysoft
public int withdraw(int amount) throws
NotEnoughMoneyException {
if (amount > this.balance)
throw new NotEnoughMoneyException ();
this.balance = this.balance – amount;
}
93. Smell: Ignored Checked Exception
93
Copyright@2013 Teddysoft
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 }
}
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”);
}
}
94
Copyright@2013 Teddysoft
95. Smell: Unprotected Main Program
95
Copyright@2013 Teddysoft
static public void main(String[] args) {
MyApp myapp = new MyApp();
myapp.start();
}
96. Avoid Unexpected Termination with
Big Outer Try Block
96
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
106. Introduce Checkpoint Class
106
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