[Java] 异常处理

异常处理方式:

1. try-catch-finally

  try{

    可能发生异常的代码

  }

  catch(异常类型1 异常名1){

    处理异常的程序代码

  }

  catch(异常类型2 异常名2){

    处理异常的程序代码

  }

  ...

  finally{

    前面无法处理的异常,在此解决

  }

2. throws:在方法中声明抛出异常

返回值 方法名() throws 异常1,异常2,...

eg:

import java.io.*;

public class Example{

  public static void main(String[] args){

    try{

      out(); 

    }catch(ArithmeticException e){

      System.out.print("除数不能是0");

    }

  }

  public static void out() throws ArithmeticException {

    int i = 9/0;

    System.out.print(i);

  }

}

3. throw: 抛出异常

import java.io.*;

public class Example{

  static int k = 0;

  public static void main(String[] args){

    try{

      out(); 

    }catch(ArithmeticException e){

      System.out.print("除数不能是0");

    }

  }

  public static void out() throws ArithmeticException {

    if (k == 0)  throw new ArithmeticException();

    int i = 9/k;

    System.out.print(i);

  }

}

4. throw 和 throws 区别

throws 是声明可能抛出异常,而throw 是一定抛出异常

throws用于方法头部,而throw 用于方法体中

5. 自定义异常

Java 允许程序员自定义异常类以处理各种系统未定义的异常。程序员可通过继承Exception 或其子类(比如IOException)来创建自己的异常类。

eg:

import java.io.*;

public class Example{

  static int k = 0;

  public static void main(String[] args){

    try{

      if(k == 0)  throw new MyException();

      int i = 5 / k;

    }catch(MyException e){

      System.out.print(e.toString());

    }

  }

  class MyException extends Exception{

    public MyException(){

      super("除数不能是0");

    }

    public MyException(String str){

      super(str);

    }

  }

}

posted @ 2015-08-19 10:57  *飞飞*  阅读(139)  评论(0编辑  收藏  举报