您的位置:首页 > 其它

异常处理Demo

2016-07-02 21:49 831 查看
/*

Exception中有一个特殊的子类异常RuntimeException运行异常

如果在函数内容抛出该异常,函数上可以不用声明,编译一样通过.

如果在函数上声明了该异常.调用者可以不用进行处理.编译一样通过;

之所以不用在函数上声明,是因为不需要让调用者处理.

当该异常发生,希望程序停止.因为在运行时,出现了无法继续运算的情况,希望停止程序后,

对代码进行修正.

自定义异常时,如果该异常的发生,无法在继续进行运算,

就让自定义异常继承RuntimeException.

对于异常分两种

1.编译时被检测的异常.

2.编译时不被检测的异常(运行时异常.RuntimeException以及其子类)

*/

/*

Java中的异常分为两大类:

  1.Checked Exception(非Runtime Exception)

  2.Unchecked Exception(Runtime Exception)

运行时异常

  RuntimeException类是Exception类的子类,它叫做运行时异常,Java中的所有运行时异常都会直接或者间接地继承自RuntimeException类。

  Java中凡是继承自Exception,而不继承自RuntimeException类的异常都是非运行时异常。

*/

class FuShuException extends RuntimeException//运行时异常

{
//private String msg;
FuShuException(String msg)
{
super(msg);//参数传给父类
}
/*public String getMessage()
{
return msg;
}*/

}

class Demo

{
int div(int a,int b)//throws FuShuException//必须为具体的异常,如果是RutimeException则不用声明异常
{
if(b<0)
throw new FuShuException("出现了除数为负数了");
if (b==0)
   throw new ArithmeticException("被零除啦");
return a/b;
}

}

class  ExceptionDemo4

{
public static void main(String[] args) 
{
Demo d = new Demo();
//try{
int x = d.div(4,0);
System.out.println("x="+x);
//}
//catch{}
System.out.println("over");
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  异常 抛出