1.异常发生过程:
发生问题时,jvm将已知的问题封装成对象,并抛给调用者主函数,主函数没有针对性的处理方式,就
继续往外抛给调用者jvm,jvm用默认处理方式,在控制台显示问题的名称,信息,位置。
2.运行时异常RuntimeException:
当throw抛出RuntimeException及其子类异常对象时,函数上可不用throws声明,提示调用者修改代码。
3.处理方式:
(1)声明&抛出异常
throws
声明异常,调用者可给出预先处理方式。它用在函数上,后面可跟多个异常类。
throw
抛出异常给调用者。用在函数内,后面跟异常对象。
Class ThrowsDemo
{
int ss(int a,int b)/*throws Exception//提示调用者处理异常(声明异常)*/
{
if(b==0)
throw new ArithmeticException("b不能为0");//抛出异常
return a/b;
}
}
public class Demo
{
public static void main(String[] args)//throws Exception
{
ThrowsDemo td = new ThrowsDemo();
int num = td.ss(11, 0);
System.out.println(num+"num");
}
}
(2)捕获异常:
try
{
//有可能发生异常的代码;
}
catch(异常类 变量)//接收异常对象
{
//处理代码;
}
finally
{
//一定会执行的代码;
}
(3) 自定义异常:
class SumException extends RuntimeException
{
public SumException()
{
super();
}
SumException(String message)
{
super(message);//子类信息都传递给父类
}
}
class Pan
{
double kid(double height,double weight){
if (height<0)
throw new PanException("身高不能小于0");
if (weight<0)
throw new PanException("体重不能小于0");
return height + weight;
}
}
public class Demo
{
public static void main(String[] args){
Pan p = new Pan();
try
{
double sum = p.kid(1.73,-115.5);
System.out.println("height + weight = "+sum);
}
catch (Exception e )
{
System.out.println(e.toString());//打印名称+异常信息
}
}
}