为什么 IOException 不工作但转到 InputMismatchException
how come the IOException isn't working but goes to the InputMismatchException
我不明白为什么这个简单的方法不会捕获异常,而是抛出另一个异常。弹出的异常错误是java.util.InputMismatchException
。
我该怎么做才能捕捉到 IOException
?
public class Throwing {
public static void main(String[] args) {
try {
int x = getInt();
System.out.println(x);
} catch (IOException a) {
a.printStackTrace();
}
}
public static int getInt() throws IOException {
int a = 0;
System.out.println("Enter an interger: ");
Scanner input = new Scanner(System.in);
a = input.nextInt();
return a;
}
}
如果您查看 JavaDocs for Scanner#nextInt,您会发现它能够抛出 InputMismatchException,等等
But the goal is that I'm trying to throw an IOException rather than InputMismatch. Is there anything i can do to my code which will help me throw it?
您将需要捕获任何可能的异常并抛出新的 IOException
并以旧的 Exception
作为原因。
public static int getInt() throws IOException
{
int a = 0;
System.out.println("Enter an interger: ");
Scanner input = new Scanner(System.in);
try {
a = input.nextInt();
} catch (InputMismatchException ime) {
throw new IOException("Could not get int from input", ime);
}
return a;
}
恕我直言,这不是最绝妙的主意,因为您可能希望以不同于 IOException
的方式对待 InputMismatchException
,这可能是在您创建 Scanner
[ 时引起的=18=]
我不明白为什么这个简单的方法不会捕获异常,而是抛出另一个异常。弹出的异常错误是java.util.InputMismatchException
。
我该怎么做才能捕捉到 IOException
?
public class Throwing {
public static void main(String[] args) {
try {
int x = getInt();
System.out.println(x);
} catch (IOException a) {
a.printStackTrace();
}
}
public static int getInt() throws IOException {
int a = 0;
System.out.println("Enter an interger: ");
Scanner input = new Scanner(System.in);
a = input.nextInt();
return a;
}
}
如果您查看 JavaDocs for Scanner#nextInt,您会发现它能够抛出 InputMismatchException,等等
But the goal is that I'm trying to throw an IOException rather than InputMismatch. Is there anything i can do to my code which will help me throw it?
您将需要捕获任何可能的异常并抛出新的 IOException
并以旧的 Exception
作为原因。
public static int getInt() throws IOException
{
int a = 0;
System.out.println("Enter an interger: ");
Scanner input = new Scanner(System.in);
try {
a = input.nextInt();
} catch (InputMismatchException ime) {
throw new IOException("Could not get int from input", ime);
}
return a;
}
恕我直言,这不是最绝妙的主意,因为您可能希望以不同于 IOException
的方式对待 InputMismatchException
,这可能是在您创建 Scanner
[ 时引起的=18=]