C#不需要异常变量

本文关键字:变量 异常 不需要 | 更新日期: 2023-09-27 18:00:30

在下面的代码中,没有为IndexOutOfRangeException-声明对象

class ExcDemo1 {
    static void Main() {
        int[] nums = new int[4];
        try {
            Console.WriteLine("Before exception is generated.");
            // Generate an index out-of-bounds exception.
            for(int i=0; i < 10; i++) {
                nums[i] = i;
                Console.WriteLine("nums[{0}]: {1}", i, nums[i]);
            }
            Console.WriteLine("this won't be displayed");
        }
        catch (IndexOutOfRangeException) {
            // Catch the exception.
            Console.WriteLine("Index out-of-bounds!");
        }
        Console.WriteLine("After catch block.");
    }
}

我只是想知道这是允许的吗?若可以,我们也可以在java中做同样的事情吗?这样做的好处是什么?

C#不需要异常变量

catch (IndexOutOfRangeException) {

C#中完全合法。如果不打算使用catch,则无需在其中指定变量。

你的问题很含糊。我想你是想问我们是否允许在下面的代码中捕获异常,而不为其声明变量
catch (IndexOutOfRangeException) { // Catch the exception. Console.WriteLine("Index out-of-bounds!"); }
如果这是你的问题?那么是的,我们可以做到。