Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagejava
titleException handling in Java
Scanner in = new Scanner(System.in);
boolean error = true;
while (error) {            
   	try {
        System.out.println("Please enter a number: h");
        int x = in.nextInt();
        error = false;       
     } catch (InputMismatchException exception) {
        System.out.println("Oops!  That was no valid number.  Try again..."); 
        in.nextLine();
     }
}
 
Code Block
languagepy
titleException handling in Python
while True:
     try:
         x = int(input("Please enter a number: "))
         break
     except ValueError:
         print("Oops!  That was no valid number.  Try again...")

The try statement in Python works as follows.

  • First, the try clause (the statement(s) between the try and except keywords) is executed.
  • If no exception occurs, the except clause is skipped and execution of the try statement is finished.
  • If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.
  • If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.

...