异常的处理

 

         一、异常的概念:所谓异常就是程序运行过程中会出现一些特殊的情况,不能正常运行。在日常生活中,问题也是一个类,也是一类具体是事物,我们可以通过java面向对象的形式把它封装成一个类。异常情况分为两种,一种是严重的,一种是不严重的,严重的情况,我们用Error来描述,通常我们不进行处理;而不严重的情况,我们用Exception类来描述,它是可以处理的:

1、Throwable类有两个子类,一个就是Error类,另一个就是Exception类。

2.处理异常的机制:格式如下:

try{     需要检测的程序;          }catch(Exception e){ 捕获的异常;    } finally{     必须执行的语句;     }

3.Throwable类中常用到的方法:

getMessage()    获取异常的信息:到底是什么错误;

toString()           获取异常的名称、信息,返回字符串;

printStrackTrace()获取异常的名称、信息、位置;

PrintStackTrace(PrintStream s )打印成为报告输出;

4.简单分析一下:throws 和throw的区别:

throws    用来声明异常,放到函数后面

throw      用来抛出异常,放到函数内部

下面用一个代码来体现这些概念:


class ExceptionDemo1
{
 public static void main(String[] args)//throws Exception //把异常抛给虚拟机处理
 {
  
   Rid r=new Rid();
   try{
   int x=r.rid(4,0);
   System.out.println("x="+x);
   }
   catch(Exception e)//Exception e=new ArithmeticException();
   //其实这是个多态的体现,Exception是一个父类,引用指向了子类的对象
  {
   System.out.println("出现异常");
   System.out.println(e.getMessage());//获取异常的信息;
   System.out.println(e.toString());//获取异常的名称、信息;toString可以不写,默认调用
   e.printStackTrace();//获取异常的名称、信息、位置;它是void类型,里面定义了打印功能,不需要输出
  }
  System.out.println("over");
 }
}
class Rid
{
 public int rid(int a,int b)throws Exception//把异常抛给调用者,就是主函数
 {
  return a/b;
 }
}
5.对应多异常的处理:

(1)、建议对异常的声明要具体化,这样处理起来更有针对性;

(2)、如果声明多个异常,那么就要对应多个catch块,但是不要定义多余的catch块。

(3)、如果catch()中,存在子父类继承的关系,那么要把父类的catch块放到最下面;

下面通过一个代码体现一下:


class ExceptionDemo2
{
 public static void main(String[] args)
 {
   Main m=new Main();
   try
   {
    int x=m.function(4,0);
    System.out.println("x="+x);
   }
   catch (ArrayIndexOutOfBoundsException e )
   {
    System.out.println("角标越界了");
   }
   catch(ArithmeticException e)
  {
   System.out.println("运算出错");
  }
   catch(Exception e)
  {
   System.out.println("chucuo");
  }
  System.out.println("over");
 }
}
class Main
{
 public int function(int a,int b)//抛异常时,声明的更加详细throws ArrayIndexOutOfBoundsException,ArithmeticException
 {
  int[]arr=new int[a];
  System.out.println(arr[4]);
  return a/b;
 }
}

 

原文地址:https://www.cnblogs.com/warrior4236/p/6055733.html