Difference between revisions of "Exception Handling - Python"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
(Created page with "=Exceptions] Exceptions are created when your program crashes, this will cause your program to fail. However you can catch exceptions and deal with them in your program, you c...")
(No difference)

Revision as of 19:41, 20 June 2018

=Exceptions] Exceptions are created when your program crashes, this will cause your program to fail. However you can catch exceptions and deal with them in your program, you could essentially correct the original error and carry on.

Catching Exceptions

To use exception handling in Python, you first need to have a catch-all except clause. The words "try" and "except" are Python keywords and are used to catch exceptions.The code within the try clause will be executed statement by statement. If an exception occurs, the rest of the try block will be skipped and the except clause will be executed.

For example:

try:
    some statements here
except:
    exception handling

Let's see a short example on how to do this:

try:
    print 1/0

except ZeroDivisionError:
    print "You can't divide by zero, you're silly."

You can catch multiple exceptions from a single try block, the common ones are:

except IOError:
    print('An error occurred trying to read the file.')

except ValueError:
    print('Non-numeric data found in the file.')

except ImportError:
    print "NO module found"

except EOFError:
    print('Why did you do an EOF on me?')

except KeyboardInterrupt:
    print('You cancelled the operation.')

except:
    print('An error occurred.')