Java中自定义异常详解及实例代码

时间:2021-08-19 22:00:42

Java中自定义异常详解及实例代码

下面做了归纳总结,欢迎批评指正

自定义异常

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class ChushulingException extends Exception
{
  public ChushulingException(String msg)
  {
    super(msg);
  }
 
class ChushufuException extends Exception
{
  public ChushufuException(String msg)
  {
    super(msg);
  }
}

  自定义异常 End 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Numbertest 
{
  public int shang(int x,int y) throws ChushulingException,ChushufuException
  {
    if(y<0)
    {
      throw new ChushufuException("您输入的是"+y+",规定除数不能为负数!");//抛出异常
    }
    if(y==0)
    {
      throw new ChushulingException("您输入的是"+y+",除数不能为0!");
    }
   
    int m=x/y;
    return m;
  }
}
 
 
 
 
 
class Rt001
{
  public static void main(String[]args)
  {
    Numbertest n=new Numbertest();
 
    //捕获异常
    try
    {
      System.out.println("商="+n.shang(1,-3));
    }
    catch(ChushulingException yc)
    {
      System.out.println(yc.getMessage());
      yc.printStackTrace();
    }
    catch(ChushufuException yx)
    {
      System.out.println(yx.getMessage());
      yx.printStackTrace();
    }
    catch(Exception y)
    {
      System.out.println(y.getMessage());
      y.printStackTrace();
    }
   
  finally{ System.out.println("finally!");} ////finally不管发没发生异常都会被执行 
 
  }
}
/*

[总结]  

1.自定义异常: 

?
1
2
3
4
5
6
7
8
class 异常类名 extends Exception
{
  public 异常类名(String msg)
  {
    super(msg);
  }
}

2.标识可能抛出的异常:  

throws 异常类名1,异常类名2  

3.捕获异常: 

?
1
2
3
try{}
catch(异常类名 y){}
catch(异常类名 y){}

 4.方法解释  

?
1
2
getMessage() //输出异常的信息
printStackTrace() //输出导致异常更为详细的信息

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!