异常就是与我们编译相违背在过程中出现的逻辑或忘记一些赋值等等

分为编译时错误和运行时错误

运行时异常

JAVA常用工具类异常处理

 我们一般处理的时Exception异常;

异常处理

异常处理可以通过关键字try,catch,finally,throw,throws;

try,catch,finally处理 捕获异常

try捕获异常,通常把try放在我们觉得出错的位置;

catch 捕获异常,当异常出现时,被catch捕获通过Exception方法来提示异常(通常从异常最后一行开始处理异常);

finally

 

无论前面出现什么都会直接下面语句;

package com.jiedada.exception;

import java.util.Scanner;

public class Frist {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
   int x=0,y=0;
      
      System.out.println("=============运行开始=========");
      Scanner sc=new Scanner(System.in);
      try {
      System.out.println("请输入分子");
       x=sc.nextInt();
      System.out.println("请输入分母");
       y=sc.nextInt();
      }
      catch(Exception e)
      {
      System.out.println("================程序结束=========");
      e.printStackTrace();
      }
      finally {
      System.out.println("该算术表达式结果为"+(x/y));
      }
    }

}

 

 

catch可以使用多个子类的方法来判断属于那种类型的错误如ArithmeticException(算术表达式的错误)

在多个cat表达式中最后一个catch中最好或者一定要包含一个Exception的子方法表达式这样才能检查所有错误;

InputMismatchException(判断输入的类型不是不错的

package com.jiedada.exception;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Frist {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
   int x=0,y=0;
      
      System.out.println("=============运行开始=========");
      Scanner sc=new Scanner(System.in);
      try {
      System.out.println("请输入分子");
       x=sc.nextInt();
      System.out.println("请输入分母");
       y=sc.nextInt();
       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)
      {
      System.out.println("出错啦---");
      e.printStackTrace();
      }
      finally {
          System.out.println("================程序结束=========");
      }
    }

}
View Code

相关文章:

  • 2021-11-25
  • 2021-10-27
  • 2022-02-08
  • 2022-01-10
  • 2022-12-23
  • 2021-08-08
  • 2021-10-16
猜你喜欢
  • 2021-12-06
  • 2022-12-23
  • 2021-11-30
  • 2021-08-06
  • 2021-05-11
相关资源
相似解决方案