搞懂java例外處理的難題:checked與unchecked exceptions不再是問題
DESCRIPTION
討論Java語言中checked與unchecked exceptions使用上的問題TRANSCRIPT
Teddy Chen [email protected]
Feb. 21 2013
Copyright@2013 Teddysoft
3
系統不穩定
4
5
6
7
Problem
8
Problem
Copyright@2013 Teddysoft
• Correctness – Contract Specification(超出範圍)
• Robustness – Exception Handling
Copyright@2013 Teddysoft
Copyright@2013 Teddysoft
Copyright@2013 Teddysoft
RuntimeException
Throwable
Exception Error
Unchecked Exception
Checked Exception
Copyright@2013 Teddysoft
handle
declare
Copyright@2013 Teddysoft
Copyright@2013 Teddysoft
• Checked exceptions for recoverable conditions –打死不知道要如何去recover 任何東東?
Copyright@2013 Teddysoft
class FileService {
…
public copy (String s)
throws IOException {
…
if (error)
throw new
IOException(“reason”);
}
}
backup () {
FileService fs = new
FileService();
try {
fs.copy(“a.txt”);
}
catch (IOException e){
// exception handling code
}
}
Copyright@2013 Teddysoft
1
2
3
Copyright@2013 Teddysoft
1
2
3
• 我就是不喜歡checked exception,咬我啊!
• 例如,Standard Widget Toolkit (SWT, Eclipse的UI元件)只使用unchecked exception:
– SWTException用來表示可修復的SWT錯誤。
– SWTError則用來表示不可修復的錯誤。
Copyright@2013 Teddysoft
Copyright@2013 Teddysoft
Spring
Framework
Java
Your
application
checked
unchecked DataAccessException
SQLException
technology-
specific
HibernateException
technology-
specific
Copyright@2013 Teddysoft
• Exception Type
• Recoverability
• Application Context
• Robustness Level
– G1: Error-reporting (錯誤回報)
– G2: State-recovery (狀態回復)
– G3: Behavior-recovery (行為回復)
• Exception Handling Policy
Copyright@2013 Teddysoft
Copyright@2013 Teddysoft
Copyright@2013 Teddysoft
Copyright@2013 Teddysoft
練習1: 如果Accepter收到一個 IOException,鄉民們第一個反應是什麼?
練習2: 如果Accepter收到一個 RuntimeException,鄉民們第一個反應是什麼?
Presentation
Layer
Application
Layer
Service Layer E 2. rethrow
4. wrap
Message
5. report
3. recover
E'
E''
JVM1. throwE
AppWin
GameServer
Acceptor
Copyright@2013 Teddysoft
練習3: 如果Accepter收到一個 IOException,鄉民們該如何處置?
練習4: 如果Accepter收到一個 RuntimeException,鄉民們該如何處置?
Presentation
Layer
Application
Layer
Service Layer E 2. rethrow
4. wrap
Message
5. report
3. recover
E'
E''
JVM1. throwE
AppWin
GameServer
Acceptor
Copyright@2013 Teddysoft
練習5: 如果Accepter收到一個 IOException,鄉民們該如何處置?
練習6: 如果GameServer收到 IOException ,鄉民們該如何處置?
Presentation
Layer
Application
Layer
Service Layer E 2. rethrow
4. wrap
Message
5. report
3. recover
E'
E''
JVM1. throwE
AppWin
GameServer
Acceptor
Copyright@2013 Teddysoft
練習7: Accepter的RL要設為多少?
練習8: GameServer的RL要設為多少?
Presentation
Layer
Application
Layer
Service Layer E 2. rethrow
4. wrap
Message
5. report
3. recover
E'
E''
JVM1. throwE
AppWin
GameServer
Acceptor
Copyright@2013 Teddysoft
練習9: Acceptor這一層有哪些policy可用?
練習10: GameServer這一層有哪些policy可用?
Presentation
Layer
Application
Layer
Service Layer E 2. rethrow
4. wrap
Message
5. report
3. recover
E'
E''
JVM1. throwE
AppWin
GameServer
Acceptor
30 Copyright@2013 Teddysoft