Presentation is loading. Please wait.

Presentation is loading. Please wait.

Python’s Errors and Exceptions

Similar presentations


Presentation on theme: "Python’s Errors and Exceptions"— Presentation transcript:

1 Python’s Errors and Exceptions
Lakshay Puniani

2 Types of Errors There are two types of errors: Syntax Errors
Exceptions

3 Syntax Errors Syntax Errors (Parsing Errors) are obtained during compilation. Example: >>> while True print 'Hello world' File "<stdin>", line 1, in ? while True print 'Hello world‘ ^ SyntaxError: invalid syntax When a syntax error is detected, the filename and line number are printed. The line is repeated and an arrow(^) is placed at the token where the error was detected.

4 Exceptions Exceptions are encountered during execution of the code.
Exceptions are usually not handled by the program. If exceptions are not handled, the execution of the program is stopped and an error message is displayed. The filename and line number are displayed. Also displays the type of error and what caused it. There are many built in exceptions, but can also be user defined.

5 Exceptions (examples)
>>> 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

6 Handling Exceptions Try….except statements are used for handling exceptions. >>> while True: ... try: x = int(raw_input("Please enter a number: ")) break ... except ValueError: print "Oops! That was no valid number. Try again..." First, the try clause is executed. If no exception occurs, the except clause is skipped and execution of the try statement is completed. If an exception occurs, the except clause of the matching exception type is executed. The rest of the try clause is executed after this.

7 Handling Exceptions(cont.)
If the exception does not match the type of the except clause, an error occurs. An except clause can have more than 1 type: ... except (RuntimeError, TypeError, NameError): ... Pass Exceptions can also be handled for functions. >>> def this_fails(): ... x = 1/0 ... >>> try: this_fails() except ZeroDivisionError as detail: print 'Handling run-time error:', detail ... Handling run-time error: integer division or modulo by zero

8 Else The else clause follows all except clauses.
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() If the except clause is not executed, else is executed. It is better to use else than writing more code in the try clause to avoid accidentally finding exceptions in the clause that were not expected.

9 Exception Variables If an exception has an associated value, this value can be stored in a variable. These variables are stored in instance.args. >>> 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 A user defined exception can also be raised.
>>> raise NameError('HiThere') Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: HiThere Must be either an exception instance or an exception class.

11 Raising Exception(cont.)
Exception can be raised inside a try block. >>> 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 User Defined Exceptions
New exceptions can be defined by creating a new exception class. Exceptions should be derived from the exceptions class, either directly or indirectly. >>> class MyError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) ... >>> try: raise MyError(2*2) except MyError as e: print 'My exception occurred, value:', e.value My exception occurred, value: 4 >>> raise MyError('oops!') Traceback (most recent call last): File "<stdin>", line 1, in ? __main__.MyError: 'oops!'

13 Clean Up Actions An exception can stop the execution of the try clause. Finally clause can be used after the try…except clauses. Finally clause is always executed, if an exception occurs or not. Finally clause can be used to close files that are left open or release resources that were allocated during execution.

14 Finally(example) >>> 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'

15 Predefined Clean Up Actions
Some objects define standard clean-up actions to be taken when the object is no longer needed. >>>>for line in open("myfile.txt"): print line Prints each line in myfile.txt, but leaves the file open. The with statement allows objects like files to be used in a way that ensures they are always cleaned up promptly and correctly. >>>>with open("myfile.txt") as f: for line in f: After each with statement is executed, the file f is closed.

16 Questions?


Download ppt "Python’s Errors and Exceptions"

Similar presentations


Ads by Google