當你認為例外並不適合在該段程式碼處理時
就可以考慮將例外拋出
舉例來說, 原本的程式碼是
static void openSocket(){
try {
ServerSocket ss = new ServerSocket(-10);
} catch (IOException e) {
e.printStackTrace();
}
}

可以利用throws將例外拋出
static void openSocket() throws IOException {
ServerSocket ss = new ServerSocket(-10);
}
這樣在呼叫該method的地方進行處理

還有一種是自行拋出例外
也就是利用throw來進行
static void openSocket() throws IOException {
throw new IOException("自己拋出");
}

 

1. 官網https://docs.oracle.com/javase/tutorial/essential/exceptions/declaring.html

01.png  

arrow
arrow

    RX1226 發表在 痞客邦 留言(0) 人氣()