Java学习笔记31:捕获异常try-catch语句

//异常处理通常用try-catch-finally语句实现
 package Demo_exception;
    import java.util.Scanner;
    public class Test1_Exception {
    	public static void main(String[] args) {
    		Scanner input =new Scanner(System.in);
    		System.out.println("----除法运算----");
    		try{//可能发生异常的代码
    			System.out.println("请输入被除数:");
    			int x=input.nextInt();
    			System.out.println("请输入除数:");
    			int y=input.nextInt();//y=0出现异常
    			System.out.println("结果为:"+(x/y));
    		}catch (ArithmeticException e){//打印异常
    			System.out.println("被除数0的异常");
    			e.printStackTrace();//输出堆栈中的异常信息
    		}catch(InputMismatchException e){
    				System.out.println("用户输入类型错误");
    				e.printStackTrace();
    		}catch(Exception e){//捕获该类型的语句必须放最后,由于其是所有异常类的父类
    					e.printStackTrace();
    					}
    		}
    }

猜你喜欢

转载自blog.csdn.net/qq_30242987/article/details/85853591
今日推荐