温馨提示×

在Java中如何通过try catch实现自定义异常

小樊
99
2024-08-15 13:54:37
栏目: 编程语言

在Java中,我们可以通过在try块中抛出自定义异常并在catch块中捕获该异常来实现自定义异常。下面是一个简单的示例:

首先,定义一个自定义异常类,例如MyException:

public class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}

然后,在程序中使用try catch块来捕获自定义异常:

public class Main {
    public static void main(String[] args) {
        try {
            // 模拟抛出自定义异常
            throw new MyException("This is a custom exception");
        } catch (MyException e) {
            System.out.println("Caught custom exception: " + e.getMessage());
        }
    }
}

在上面的示例中,我们在try块中抛出了自定义异常MyException,并在catch块中捕获并处理该异常。

运行上面的程序会输出:

Caught custom exception: This is a custom exception

0