使用 try…catch…finally 处理异常

异常处理是通过try-catch-finally语句实现的。
  try {
    ...... //可能产生异常的代码
  } catch( ExceptionName1 e ) {
    ...... //当产生ExceptionName1型异常时的处置措施
  } catch( ExceptionName2 e ) {
    ...... //当产生ExceptionName2型异常时的处置措施
  } [finally {
    ...... //无条件执行的语句
  } ]

异常处理举例
public class Test8_2 {
  public static void main(String[] args) {
    String friends[]={"lisa","bily","kessy"};
    try {
      for(int i=0;i<5;i++) {
        System.out.println(friends[i]);
      }
    } catch(ArrayIndexOutOfBoundsException e) {
      System.out.println("index err");
    }
    System.out.println("\nthis is the end");
  }
}

运行结果:
  lisa
  bily
  kessy
  index err

  this is the end

public class DivideZero1{
  int x;
  public static void main(String[] args) {
    int y;
    DivideZero1 c=new DivideZero1();
    try{
      y=3/c.x;
    } catch(ArithmeticException e){
      System.out.println("divide by zero error!");
    }
    System.out.println("program ends ok!");
  }
}

运行结果:
  divide by zero error!
  program ends ok!


 public class TestTryCatchFinally {
public static void main(String[] args) { try {
int i = 10;
int j = i / 0;
}catch (NullPointerException e) {
System.out.println(e.getMessage());
}catch(ClassCastException e) {
System.out.println(e.getMessage());
}catch(Exception e) {
System.out.println(e.getMessage());
} finally{
System.out.println("finally...");
} //不论在try、catch代码块中是否发生了异常事件,finally块中的语句都会被执行。 System.out.println("end..."); //示例编译时异常, IO 异常属于编译时异常. try {
InputStream is = new FileInputStream("abc.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

捕获异常

try
捕获异常的第一步是用try{…}语句块选定捕获异常的范围,将可能出现异常的代码放在try语句块中。
catch (Exceptiontype e)
在catch语句块中是对异常对象进行处理的代码。每个try语句块可以伴随一个或多个catch语句,用于处理可能产生的不同类型的异常对象。

如果明确知道产生的是何种异常,可以用该异常类作为catch的参数;也可以用其父类作为catch的参数
可以用ArithmeticException类作为参数,也可以用RuntimeException类作为参数,或者用所有异常的父类Exception类作为参数。但不能是与ArithmeticException类无关的异常,如NullPointerException,那么,catch中的语句将不会执行。

捕获异常的有关信息:
与其它对象一样,可以访问一个异常对象的成员变量或调用它的方法。
getMessage( ) 方法,用来得到有关异常事件的信息
printStackTrace( )用来跟踪异常事件发生时执行堆栈的内容。

finally
捕获异常的最后一步是通过finally语句为异常处理提供一个统一的出口,使得在控制流转到程序的其它部分以前,能够对程序的状态作统一的管理。不论在try、catch代码块中是否发生了异常事件,finally块中的语句都会被执行
finally语句是可选的

运行时异常和编译时异常

前面但使用的异常都是RuntimeException类或是它的子类,这些类的异常的特点是:即使没有使用try和catch捕获,Java自己也能捕获,并且编译通过 ( 但运行时会发生异常使得程序运行终止 )。

如果抛出的异常是IOException类的异常,则必须捕获,否则编译错误。

IOException 异常处理举例

public class Test8_3{
  public static void main(String[] args) {
    FileInputStream in=new FileInputStream("myfile.txt");
    int b;
    b = in.read();
    while(b!= -1) {
      System.out.print((char)b);
     b = in.read();
    }
    in.close();
  }
}

public class Test8_3 {
  public static void main(String[] args) {
    try{
      FileInputStream in=new FileInputStream("myfile.txt");
      int b;
      b = in.read();
      while(b!= -1) {
        System.out.print((char)b);
        b = in.read();
      }
      in.close();
    }catch (IOException e) {
      System.out.println(e);
    }finally {
      System.out.println(" It’s ok!");
    }
  }
}

异常处理----使用 try…catch…finally 处理异常的更多相关文章

  1. C++异常处理:try,catch,throw,finally的用法

    写在前面 所谓异常处理,即让一个程序运行时遇到自己无法处理的错误时抛出一个异常,希望调用者可以发现处理问题. 异常处理的基本思想是简化程序的错误代码,为程序键壮性提供一个标准检测机制. 也许我们已经使 ...

  2. java的异常处理机制(try…catch…finally)

    1 引子try…catch…finally恐怕是大家再熟悉不过的语句了,而且感觉用起来也是很简单,逻辑上似乎也是很容易理解.不过,我亲自体验的“教训”告诉我,这个东西可不是想象中的那么简单.听话.不信 ...

  3. 异常处理(try...catch...final 和 throw , throws)

    1.传统(弱语言)处理异常方式 原理:利用判断来控制异常出现 publicclass Test01 { publicstaticvoid main(String[] args) { Scanner s ...

  4. 异常处理(try catch throw)详解(C++)

    选择异常处理的编程方法的具体原因如下: 1.把错误处理和真正的工作分开来: 2.代码更易组织,更清晰,复杂的工作任务更容易实现: 3.毫无疑问,更安全了,不至于由于一些小的疏忽而使程序意外崩溃了: 4 ...

  5. 22 C#中的异常处理入门 try catch throw

    软件运行过程中,如果出现了软件正常运行不应该出现的情况,软件就出现了异常.这时候我们需要去处理这些异常.或者让程序终止,避免出现更严重的错误.或者提示用户进行某些更改让程序可以继续运行下去. C#编程 ...

  6. 异常处理之多重catch

    package com.sxt.exception.test1; import java.util.InputMismatchException; import java.util.Scanner; ...

  7. 异常处理之try catch finally

    package com.sxt.wrapper.test2; /* 0418 * 异常处理 * 采用异常处理的好处:保证程序发生异常后可以继续执行 * e.printStaceTrace:打印堆栈信息 ...

  8. 异常处理的方式二:throws+异常类型

    package com.yhqtv.demo01Exception; import java.io.File; import java.io.FileInputStream; import java. ...

  9. C++异常处理(try catch throw)完全攻略

    程序运行时常会碰到一些异常情况,例如: 做除法的时候除数为 0: 用户输入年龄时输入了一个负数: 用 new 运算符动态分配空间时,空间不够导致无法分配: 访问数组元素时,下标越界:打开文件读取时,文 ...

随机推荐

  1. Windows和linux虚拟机之间联网实现SSH远程连接以及VMware的3种网络模式[NAT、桥接和Host-only]

    Windows和linux虚拟机之间联网实现SSH远程连接以及VMware的3种网络模式[NAT.桥接和Host-only] 作者:天齐 一.Windows和linux虚拟机之间联网实现SSH远程连接 ...

  2. git 命令删除远程分支

    删除 服务器上的分支: git push origin :sxz 分支名 注意 origin 后面的空格:

  3. css3实现3d显示效果

    <!doctype html><html><head>    <meta charset="UTF-8">    <meta ...

  4. 利用eclipse中的各种功能帮助你理解代码

    @菜单栏下面,工具栏,有一对黄色的箭头按钮,一个指向左边,一个指向右边,快捷键是Alt+Left/Alt+Right 功能是跳转到你刚刚编辑过的地方 这里的Left/Right指的是左右方向键,可以方 ...

  5. FreeRTOS 任务栈大小确定及其溢出检测

    以下转载自安富莱电子: http://forum.armfly.com/forum.php FreeRTOS 的任务栈设置不管是裸机编程还是 RTOS 编程,栈的分配大小都非常重要. 局部变量,函数调 ...

  6. 使用conda 对gcc进行升级 (sonicparanoid)

    由于要是用python 3.6版本的一个包sonicparanoid,但是系统的gcc比较老,所以先用conda创建python环境,在该环境下尽心gcc的安装和升级 conda create --n ...

  7. contiki bsp

    1 lpc1768  git clone https://github.com/bolandi/contiki.git 2 efm32    git clone https://github.com/ ...

  8. VS2010在C#头文件中添加文件注释的方法(转)

    步骤: 1.VS2010 中找到(安装盘符以D盘为例)D:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ItemTempl ...

  9. 用window调用kjb和ktr

    1.    运行cmd,进入kettle的目录cd C:\soft\kettle\data-integration 2.    运行start pan.bat命令 Pan—转换执行器(命令行方式),一 ...

  10. e581. Animating an Array of Images in an Application

    This is the simplest application to animate an array of images. import java.awt.*; import javax.swin ...