异常处理

捕获异常

java的异常处理通过try-catch-finally来实现:
try运行一段程序,如果出现异常,系统throw一个异常,可通过异常类型catch并处理,或者finally由缺省处理器来处理。
try:try{…}来指定捕获并处理一段代码,该段代码可能会抛出一个或多个异常,catch进行捕获时也要进行相应处理
catch
- 一个try语句可能包含**一个或多个**catch语句
- catch语句有一个形式参数用于指明其所能捕获的异常类型,运行时系统通过参数值把被抛出的例外对象传递给catch语句
- 一般应按照try代码块中异常产生的顺序及真正类型来捕获和处理,尽量避免选择最一般的类型作为catch语句中指定要捕获的类型
- 也可以用一个catch语句来处理多个异常,这时他的异常类型应是这多个异常类型的父亲,但这种方式在程序中不能确切判断异常的具体类型

    public static void main(String[] args) {
            try{
                FileInputStream fis=new FileInputStream("text1.txt");
                int b;
                while((b=fis.read())!=-1)
                    System.out.print(b);
                fis.close();
            }
            catch(FileNotFoundException e){}
            catch(IOException e){}/*catch(Exception e){}处理多个异常*/
        }

finally:为异常处理提供一个统一的出口,使得控制流程转到程序其他部分之前,对程序状态作统一管理,无论try和catch如何执行或是否错误,finally都会执行,一般finally用来做资源清除工作,如关闭文件等


常见的异常:
- ArithmeticException
- ArrayIndexOutOfBandsException
- ArrayStoreException
- IOException
- FileNotFoundException
- NullPointerException
- MalformedURLException
- NumberFormatException
- OutOfMemoryException
使用能产生异常的方法时,如果没有捕获和处理异常,则会产生程序编译错误。


声明并抛出异常

声明异常的方法为在产生异常的方法后加上要throws出的异常的列表,throws语句可以同时指明多个异常,说明该方法不对这些异常进行处理,而是抛弃他们

  public int compute(int x)throws ArithmeticException{
    int z=100/x;
    return z;
}
public method {
    int x;
    try{
        x=System.in.read();
        compute(x);
            }
    catch(IOException ioe){
        System.out.println("read error");
    }
    catch(ArithmeticException e){
        System.out.println("divided by 0");
    }
}

这样产生异常不会由compute来处理,而是由method处理。

用一张图来表示抛出异常就很容易理解:
抛出例外


创建自己的异常

例外是一个类,自定义例外必须继承自ThrowableException类,建议用Excrption类,一般不能作为Error的子类,因为Error通常用来表示系统内部的严重故障。

public class NumberRangeException extends Exception{
    public NumberRangeException(String msg){
        super(msg);
    }
}

public int CalAnswer(String s1,String s2) throws NumberRangeException{
    int i1,i2;
    int answer=-1;
    try{
        i1=Integer.parseInt(s1);
        i2=Integer.parseInt(s2);
        if(i1<10||i1>20||i2<10||i2>20){
            NumberRangeException e=new NumberRangeException("Number not within the specifitied range.");
            throw e;
        }
        answer=i1+i2;
        catch(NumberRangeException e){
            System.out.println(e.toString());
        }
    }
    return answer;
}

public void getAnswer(){
    String answerStr;
    try{
        int answer=CalAnswer("12","5");
        answerStr=String.valueOf(answer);
    }catch(NumberRangeException e){
        answerStr=e.getMessage();
    }
    System.out.println(answerStr);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值