温馨提示×

如何在switch中处理异常情况

小樊
82
2024-09-03 14:07:52
栏目: 编程语言

在Java中,可以使用default关键字来处理switch语句中的异常情况

public class SwitchExceptionHandling {
    public static void main(String[] args) {
        int number = 5;

        switch (number) {
            case 1:
                System.out.println("Number is 1");
                break;
            case 2:
                System.out.println("Number is 2");
                break;
            default:
                System.out.println("Number is not 1 or 2, handle exception here");
                // 在这里处理异常情况,例如记录日志、抛出自定义异常等
                break;
        }
    }
}

在这个示例中,变量number的值为5,与case 1case 2不匹配。因此,程序将执行default分支中的代码,处理异常情况。你可以根据需要在default分支中添加任何处理逻辑。

0