You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 7 Current »

An exception is an error that happens during execution of a program. When that error occurs, Java generate an exception that can be handled, which avoids program to crash. 

Exceptions are convenient in many ways for handling errors and special conditions in a program. When we think that a code segment exists which can produce an error then we can use exception handling.

Example

The following example asks the user for input until a valid integer has been entered.

Exception handling in Java
Scanner in = new Scanner(System.in);
boolean error = true;
while (error) {            
   	try {
        System.out.println("Please enter a number: ");
        int x = in.nextInt();
        error = false;       
     } catch (InputMismatchException exception) {
        System.out.println("Oops!  That was no valid number.  Try again..."); 
        in.nextLine();
     }
}
If the user enters a value that isn’t a valid integer, the catch block catches the error and forces the loop to repeat.
Exception 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.

note: Although the previous example is used to present the syntax and use of exception handling, you should check whether or not the input can be parsed as an int before attempting to assign the input's value to an int. You should not be using an exception to determine whether or not the input is correct it is bad practice and should be avoided.

Exception handling in Java
 if(scanner.hasNextInt()){
   option = scanner.nextInt();
}else{
   System.out.printLn("your message");
}
This way you can check whether or not the input can be interpreted as an int and if so assign the value and if not display a message. Calling that method does not advance the scanner. 
  • No labels