java異常處理總結

來源:互聯網
上載者:User

1、java異常處理中,一個域內拋出異常(11行拋出異常,12、13行代碼不再執行),並用catch捕獲並處理後,域之後的代碼是繼續執行的(19,20行),如果域的catch後麵包含finally語句,是執行完finally裡面的代碼(17行)後,再繼續執行後續代碼(19、20行)。

 1 public class ExceptionTest {
2
3
4 class MyException extends Exception{
5
6 }
7
8 String sf1() {
9 int i = 0;
10 try{
11 if(i==0)throw new MyException();
12 System.out.println("IN");
13 return null;
14 }catch(MyException e){
15 System.out.println("CATCH");
16 }finally{
17 System.out.println("FINALLY");
18 }
19 System.out.println("OUT");
20 return null;
21
22 }
23 /**
24 * @param args
25 */
26 public static void main(String[] args){
27 // TODO Auto-generated method stub
28 new ExceptionTest().sf1();
29 }
30
31 }
//console output
CATCH
FINALLY
OUT

2、即便函數已經通過return 返回,如果返回語句外圍有catch、finally語句包圍,finally語句內容還是可以被執行的(18行)。

 1 public class ExceptionTest {
2
3
4 class MyException extends Exception{
5
6 }
7
8 String sf1() {
9 int i = 0;
10 try{
11 if(i!=0)
12 throw new MyException();
13 System.out.println("IN");
14 return null;
15 }catch(MyException e){
16 System.out.println("CATCH");
17 }finally{
18 System.out.println("FINALLY");
19 }
20 System.out.println("OUT");
21 return null;
22
23 }
24 /**
25 * @param args
26 */
27 public static void main(String[] args){
28 // TODO Auto-generated method stub
29 new ExceptionTest().sf1();
30 }
31
32 }
//console output
IN
FINALLY

3、
如果一個函式宣告了異常,函數體內通過throw拋出了此異常且外圍沒有用try、catch去捕獲的話,則函數到此執行結束,不過如果外圍有try、
finally語句,final裡面的語句還是要執行的(第14行)。不過整個域後面的代碼是不會在執行了(第16行)。

 1 public class ExceptionTest {
2
3
4 class MyException extends Exception{
5
6 }
7
8 String sf1() throws MyException {
9 int i = 0;
10 try{
11 if(i==0)throw new MyException();
12 System.out.println("IN");
13 }finally{
14 System.out.println("FINALLY");
15 }
16 System.out.println("OUT");
17 return null;
18
19 }
20 /**
21 * @param args
22 */
23 public static void main(String[] args) throws MyException {
24 // TODO Auto-generated method stub
25 new ExceptionTest().sf1();
26 }
27
28 }
//console output

FINALLY
Exception in thread "main" ExceptionTest$MyException
    at ExceptionTest.sf1(ExceptionTest.java:11)
    at ExceptionTest.main(ExceptionTest.java:25)

4、其他:

  1)函數可以聲明了異常,但不拋出。

  2)函數內部捕獲了異常,並在catch和finally裡面沒有拋出新異常的情況下,是不用函式宣告的。只有函數記憶體在沒有被捕獲的異常時,才需要函式宣告異常。

  3)子類在重構父類包含異常聲明的函數時,不能添加新的異常聲明(指不是父類方法中聲明的異常的擴充異常),但可以減少。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.