如何在switch中处理异常情况

2594
2024/9/3 15:31:34
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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 1和case 2不匹配。因此,程序将执行default分支中的代码,处理异常情况。你可以根据需要在default分支中添加任何处理逻辑。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: C语言switch语句的特点有哪些