异常
异常
try catch 语句
使用多重catch语句时,异常子类一定放在异常父类前面
捕获不到异常,则程序异常停止,try-catch语句块后语句不再执行
public class Main
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int a,b,c;
System.out.println("请输入两个数: ");
try { //截止到出现异常的语句,若被catch语句捕获到,退出try进入catch中
a=in.nextInt(); //若捕获不到,则程序异常停止,try-catch语句块后语句不再执行
b=in.nextInt();
c=a/b;
System.out.println(c);
}
catch(InputMismatchException e){ //捕获输入数据不匹配的异常
System.out.println("输入数据类型不匹配!");
}
catch(ArithmeticException e) //捕获数学异常
{
System.out.println("数学异常"+e.getMessage());
}
catch(Exception e) //异常父类
{
System.out.println("异常我全包");
}
System.out.println("感谢您的使用! ");
}
}
try-catch-finally语句
finally语句无论 try 语句是否异常,异常是否被捕获,都能执行
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a,b,c;
System.out.println("请输入两个数: ");
try { //截止到出现异常的语句,若被catch语句捕获到,退出try进入catch中
a=in.nextInt(); //若捕获不到,则程序异常停止,try-catch语句块后语句不再执行
b=in.nextInt();
c=a/b;
System.out.println(c);
}
catch(InputMismatchException e){ //捕获输入数据不匹配的异常
System.out.println("输入数据类型不匹配!");
}
finally
{
System.out.println("finally语句块总能执行");
}
System.out.println("感谢您的使用! ");
}
}
抛出
异常的分类
运行时异常
RuntimeException及其子类
编译期间不能发现
在代码中可使用try-catch-finally处理
受检异常(非运行时异常)
RuntimeException之外的类及其子类
java编译器强制要求我们处理
处理方法:
1、try-catch-finally
2、抛出(throw或throws)
异常的抛出
throw
throws
public class Calculator {
public void div(int m,int n) throws Exception
{
if(n==0)
{
throw new Exception("除数不能为零");
}
else
{
System.out.println(m/n);
}
}
public void compute() throws Exception
{
div(3,4);
}
public void compute1()
{
try {
div(3,4);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
浙公网安备 33010602011771号