标签:
public
void
consumeAndForgetAllExceptions(){
try
{
...some code that throws exceptions
}
catch
(Exception ex){
ex.printStack
trace
();
}
}
采用上面这种方式处理异常时,catch代码段接管控制权,然后catch段之后代码继续执行,好像什么都没有发生。
public
void
someMethod() throws Exception{
}
该方法内可能并不会抛出异常
总结:忽略异常或随意抛出异常是常见现象。
public
List getAllAccounts() throws
FileNotFoundException, SQLException{
...
}
public
void
dataAccessCode(){
try
{
..some code that throws SQLException
}
catch
(SQLException ex){
ex.printStack
trace
();
}
}
public
void
dataAccessCode(){
try
{
..some code that throws SQLException
}
catch
(SQLException ex){
throw
new
RuntimeException(ex);
}
}
public
class
DuplicateUsernameException
extends
Exception {
public
DuplicateUsernameException
(
String
username){....}
public
String
requestedUsername(){...}
public
String
[] availableNames(){...}
}
throw
new
Exception(
"Username already taken"
);
注:抛出什么异常参见最佳实践第一点
public
void
dataAccessCode(){
Connection conn =
null
;
try
{
conn = getConnection();
..some code that throws SQLException
}
catch
(SQLException ex){
ex.printStack
trace
();
}
finally
{
DBUtil.closeConnection(conn);
}
}
class
DBUtil{
public
static
void
closeConnection
(Connection conn){
try
{
conn.close();
}
catch
(SQLException ex){
logger.error(
"Cannot close connection"
);
throw
new
RuntimeException(ex);
}
}
}
DBUtil关闭连接工具类,最重要的部分在于finally,无论异常发不发生都会执行关闭连接操作,如果关闭发生异常会抛出一个RuntimeException。
2. 不要使用异常作控制流程之用
public
void
useExceptionsForFlowControl() {
try
{
while
(
true
) {
increaseCount();
}
}
catch
(MaximumCountReachedException ex) {
}
//Continue execution
}
public
void
increaseCount()
throws MaximumCountReachedException {
if
(count >=
5000
)
throw
new
MaximumCountReachedException();
}
try
{
..
}
catch
(Exception ex){
}
标签:
原文地址:http://www.cnblogs.com/linux007/p/5782708.html