使用 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. Oracle PLSQL Demo - 09.Open、Fetch遍历游标[Open, Fetch, Close Record CURSOR]

    declare r_emp scott.emp%rowtype; cursor cur_emp is select t.* from scott.emp t; begin open cur_emp; ...

  2. vue路由配置,vue子路由配置

    上一篇关于vue环境配置已经写好了!按照操作就行了! 现在一个项目已经部署完成,接下来我们从路由开始! 还记得在初始化项目的时候,有提示是否需要安装vue-router,对没错,vue中路由全靠它! ...

  3. Mac下Python安装目录

    /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages

  4. c++之——派生类的同名成员和函数调用方式及构造析构顺序

    #include<iostream> using namespace std; class Object { public: Object(), b(), c() { cout <& ...

  5. 一款纯css3实现的图片3D翻转幻灯片

    之前介绍了好多款网页幻灯片,今天要给大家再带来一款纯css3实现的图片3D翻转幻灯片.这款幻灯片图片轮播采用了3D翻转的形式,效果非常不错.一起看下效果图: 在线预览   源码下载 实现的代码. ht ...

  6. Apache HttpComponents POST提交带参数提交

    public class Test { public static void main(String[] args) throws IOException { DefaultHttpClient ht ...

  7. BusyBox init工作流程

    linux启动完成后,运行由Busybox产生的init进程. /sbin/init是系统启动的第一个用户进程,pid=1.init的工作是根据/etc/inittab脚本来进行系统的初始化工作,关机 ...

  8. el 表达式 强制类型转换

    el 表达式 强制类型转换 今天有人问我了这个问题 jsp页面中,能否实现 <%  request.setAttrites("a","1234");  % ...

  9. 如果通过html 链接打开app

    https://my.oschina.net/liucundong/blog/354029 <!doctype html> <html> <head> <me ...

  10. DIV+CSS 命名规范

    常用的CSS命名规则: 头:header 内容:content/container 尾:footer 导航:nav 侧栏:sidebar栏目:column 页面外围控制整体布局宽度:wrapper 左 ...