Presentation is loading. Please wait.

Presentation is loading. Please wait.

By Ryan Christen Errors and Exceptions.

Similar presentations


Presentation on theme: "By Ryan Christen Errors and Exceptions."— Presentation transcript:

1 By Ryan Christen Errors and Exceptions

2 The two types of errors Syntax Errors
-These errors are obtained when compiling. -When the error is obtained, the program will point to the line and the part of the code where it got the error. -Python basically does not know the format of the code you put in. Exceptions -These errors happen upon execution of the code. -There are many types, but the type and line will be displayed. -Most of them are not handled by programs

3 This is an example of a Python syntax error
>>> while True print 'Hello world' File "<stdin>", line 1, in ? while True print 'Hello world' ^ SyntaxError: invalid syntax 3 examples of Python exceptions >>> 10 * (1/0) Traceback (most recent call last): File "<stdin>", line 1, in ? ZeroDivisionError: integer division or modulo by zero >>> 4 + spam*3 NameError: name 'spam' is not defined >>> '2' + 2 TypeError: cannot concatenate 'str' and 'int' objects

4 Handling exceptions with Try
When try is executed, it runs the code under it If there happens to be an error, it stops the code and goes to an except of matching type If no except of matching type can be found, then it gives an error like that of prevoius example. The except clauses can hold more then 1 type Only the first except clause will respond to the error. Except clauses can not have any type in them, but this is not recommended. Try can call functions to check.

5 Example of using try >>> while True: ... try: x = int(raw_input("Please enter a number: ")) break ... except ValueError: print "Oops! That was no valid number. Try again..." ... Example of multiple except uses except (RuntimeError, TypeError, NameError): ... pass

6 Using else The else clause follows all except clauses
If the except clause is not executed, the else clause is. Putting code into an else instead of putting it outside of a try statement can protect it from other exceptions

7 Example of using else statement
for arg in sys.argv[1:]: try: f = open(arg, 'r') except IOError: print 'cannot open', arg else: print arg, 'has', len(f.readlines()), 'lines' f.close()

8 Exceptions may have variables
The exception itself can have variables bound to the exception instance. The variables will be stored in instance.args.

9 Example of what Exceptions can hold
>>> try: ... raise Exception('spam', 'eggs') ... except Exception as inst: ... print type(inst) # the exception instance ... print inst.args # arguments stored in .args ... print inst # __str__ allows args to printed directly ... x, y = inst # __getitem__ allows args to be unpacked directly ... print 'x =', x ... print 'y =', y ... <type 'exceptions.Exception'> ('spam', 'eggs') x = spam y = eggs

10 Raising Exceptions Using the raise statement, you can give yourself an error! The type of error can be specified. The arguments inside the error can describe the error. (see example). If you do not intend to handle it, put it inside of try code.

11 Example of using raise >>> raise NameError('HiThere') Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: HiThere Using raise and taking care of it >>> try: raise NameError('HiThere') ... except NameError: print 'An exception flew by!‘ Raise ... An exception flew by! Traceback (most recent call last): File "<stdin>", line 2, in ? NameError: HiThere

12 Using finally and with for cleanup
Finally is put after everything else after the try statement. It is always runs no matter what, and is good for closing anything open at the end. With is used with files so that they can clean up themselves.

13 Example showing finally always being printed out
>>> def divide(x, y): ... try: ... result = x / y ... except ZeroDivisionError: ... print "division by zero!" ... else: ... print "result is", result ... finally: ... print "executing finally clause" ... >>> divide(2, 1) result is 2 executing finally clause >>> divide(2, 0) division by zero! >>> divide("2", "1") Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 3, in divide TypeError: unsupported operand type(s) for /: 'str' and 'str'

14 Example showing proper usage of with, using with a file (yes, it gets its own slide)
with open("myfile.txt") as f: for line in f: print line

15 User-defined Exceptions
It is possible to create your own exceptions. Usually in some form they should be derived from the Exception class. Usually also create a base class, and subclass for certain examples Useful for getting information you want about an error.


Download ppt "By Ryan Christen Errors and Exceptions."

Similar presentations


Ads by Google