当前位置: 移动技术网 > IT编程>开发语言>Java > Java中自定义异常详解及实例代码

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

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

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

自定义异常

class chushulingexception extends exception 
{ 
  public chushulingexception(string msg) 
  { 
    super(msg); 
  } 
}  
 
class chushufuexception extends exception 
{ 
  public chushufuexception(string msg) 
  { 
    super(msg); 
  } 
} 

  自定义异常 end 

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.自定义异常: 

class 异常类名 extends exception 
{ 
  public 异常类名(string msg) 
  { 
    super(msg); 
  } 
} 
 

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

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

3.捕获异常: 

try{} 
catch(异常类名 y){} 
catch(异常类名 y){} 

 4.方法解释  

getmessage() //输出异常的信息 
printstacktrace() //输出导致异常更为详细的信息 

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网