异常处理

本文详细介绍了Java中的异常处理机制,包括基本写法、异常的抛出与捕获、异常分类及多异常处理等内容,并提供了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.异常(例外、差错):exception
基本写法:

try{
    语句组
    }catch(Exception ex){
        异常处理语句;
    }

例:

import java.io.*;
public class Test 
{
    public static void main(String[] args)
    { 
        try{
            BufferedReader in = new BufferedReader(
                    new InputStreamReader( System.in ) );
            System.out.print("Please input a number: ");
            String s = in.readLine();
            int n = Integer.parseInt( s );          
        }catch(IOException ex){
            ex.printStackTrace();
        }catch(NumberFormatException ex){
            ex.printStackTrace();
        }

    }

}

2.Java中的异常处理
(1)抛出(throw)异常

throw 异常对象;

(2)运行时系统在调用栈中查找
(3)捕获(catch)异常的代码

try{
    语句组;
    }catch(异常类名,异常形式参数名){
        异常处理语句组;
    }finally{
        异常处理语句组;
    }

3.异常的分类
Throwable
(1)Error:JVM的错误
(2)Exception:异常
Exception类:
构造方法:

public Exception();
public Exception(String message);
Exception(String message, Throwable cause);

方法:

getMessage()
getCause()
printStackTrace()

4.多异常处理
子类异常要排在父类异常的前面
finally语句
无论是否有异常都要执行
例:

public class Test 
{
    public static String output = "";
    public static void foo(int i)
    {
        try{
               if(i == 1)
                {
                    throw new Exception();
                }
                output += "1";
        }
        catch(Exception e)
        {
            output +="2";
            return;
        } 
        finally 
        {
            output +="3";
        }
        output += "4";
    }

    public static void main(String[] args)
    { 
        foo(1);//23
        foo(0);//134
        System.out.println(output);
    }

}

5.受检的异常
Exception分两种
(1)RuntimeException及其子类
(2)受检的异常(checked Exception)

受检的异常:
(1)catch
(2)throws

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值