public class Test {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int in_next = in.nextInt();
System.out.println(in_next + "Passed safely");
in.close();
}
}
Make something like the above and execute it. If you enter something like "oh" in the console and type it, an error will occur. What happens if you include try ~ catch in this?
public class Test {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
try{
int in_next = in.nextInt();
System.out.println(in_next + "Passed safely");
in.close();
}
catch(Exception e){
System.out.println("It's an error");
System.out.println(e);
}
}
}
I made it as shown in the figure. First, try the things in the try statement. If any error occurs there, it will move to catch. It's said to be thrown. The Exception inside the catch means an exception, which is an exception class. The exception will be in the next e. Let's run it and insert the appropriate characters. The content of the error appeared on the console. I got a java.util.InputMismatchException, so I got the same error Try to squeeze it to catch only when you wake it up.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
try{
int in_next = in.nextInt();
System.out.println(in_next + "Passed safely");
in.close();
}
catch(InputMismatchException e){
System.out.println("It's an error");
System.out.println(e);
}
}
}
You may increase catch. It's okay to write another catch. You may issue a message for each error.