码迷,mamicode.com
首页 > 其他好文 > 详细

异常及异常处理

时间:2016-09-02 18:49:29      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

/**
 * 捕获异常!
 * try{
 *        执行语句,出现异常将不再继续执行后面语句,直接跳到对应的catch异常块,
 * }catch(exception e){
 *         跳到此处后将把这里内容执行完后,如有finally语句块将执行finally语句块后结束,否则直接结束异常抛出语句块。
 * }finally {    
 *         异常语句块结束后必执行的语句块,一般用于释放内存。
 * }
 * 
 * * 抛出异常语法
 * public void 方法名() throws 异常列表{
 *         throw new 异常类型("异常信息");
 * }
 * * 自定义一个异常类
 * 语法:
 * public class 类名 extends Exception{
 *  }
 *  
 * *不能处理,抛出异常
 * public void Test1(int i) throws Exception//此处用throws,
 *    {
 *            if (i==0)
 *        {
 *            throw new Exception("i不能为“0”");//此处用throw,抛出异常为Exception或自定义时,必须自己解决或向上抛出。
 *        }
 *    }
 */

例子:

 

 1 public class Demo1
 2 {
 3     public static void main(String[] args)
 4     {
 5         System.out.println("main开始");
 6         Demo1 d=new Demo1();
 7         d.js();
 8         d.Test2();//自定义异常
 9         System.out.println("main结束");
10     }
11     
12     public void Test1(int i) throws Exception
13     {
14         if (i==0)
15         {
16             throw new Exception("i不能为“0”");
17         }
18     }
19     
20     public void Test2(){
21         try
22         {
23             throw new DemoException();
24         } catch (DemoException e)
25         {
26             e.printStackTrace();
27         }
28     }
29     
30     public void js()
31     {
32         try
33         {
34             int a=10;
35             int b=100;
36             String s=null;
37             System.out.println("while开始");
38             while(b>-1)
39             {
40                 System.out.println(s.length());
41                 a--;
42                 b=b/a;
43                 
44             }
45         }
46         catch (NullPointerException e)
47         {
48             e.printStackTrace();
49             System.out.println("空指针异常!");
50         }
51         catch (ArithmeticException e)
52         {
53             e.printStackTrace();
54             System.out.println("计算异常!");
55         } 
56         catch (Exception e)
57         {
58             e.printStackTrace();
59             System.out.println("未知异常!");
60         }
61         finally 
62         {
63             
64         }
65         System.out.println("while结束!");
66     }
67     
68 }

 

异常及异常处理

标签:

原文地址:http://www.cnblogs.com/j7672226/p/5834514.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!