951 likes | 1.93k Views
Python’s Errors and Exceptions. Nicholas Policelli. Errors and Exceptions. There are two main types of errors: Syntax Errors Exceptions. Syntax Errors. Most common type of errors >>> while True print ( 'Hello world' ) File "< stdin >", line 1, in ? while True print ( 'Hello world ')
E N D
Python’s Errors and Exceptions Nicholas Policelli
Errors and Exceptions • There are two main types of errors: • Syntax Errors • Exceptions
Syntax Errors • Most common type of errors >>> whileTrueprint('Hello world') File "<stdin>", line 1, in ? while True print ('Hello world') ^ SyntaxError: invalid syntax • The parser repeats the offending line and highlights the error. • File name and line number are also printed for reference.
Exceptions • Exceptions are errors deleted during execution • Most exceptions are not handled by programs, resulting in error messages • The last line of the error message indicates the problem
Exceptions >>> 10* (1/0) Traceback (most recent call last): File "<stdin>", line 1, in ? ZeroDivisionError: division by zero >>> 4+ spam*3 Traceback(most recent call last): File "<stdin>", line 1, in ? NameError: name 'spam' is not defined >>> '2'+2Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: Can't convert 'int' object to str implicitly
Exceptions • The string printed as the exception type si the name of the built in exception that occurred. • Ex: ZeroDivisionError, NameError, etc. • The rest of the line contains details about the exception • Ex: division by zero, name ‘spam’ is not defined, etc. • The line preceding the error message show the context of the exception • Ex: File "<stdin>", line 1, in ?
Handling Exceptions • You can write your program to handle certain exceptions • One way to do this is try >>> whileTrue: ... try: ... x =int(input("Please enter a number: ")) ... break ... exceptValueError: ... print("Oops! That was no valid number. Try again...") ...
Try Statements • A try statement may have more than one except clause to allow multiple exception types to by tried. • An except staement may name exceptions as a parenthesized triple Ex :... except (RuntimeError, TypeError, NameError): ...pass
Wildcard Exceptions • You may leave the last except clause blank to be used as a wild card. importsys try: f =open('myfile.txt') s =f.readline() i=int(s.strip()) exceptOSErroraserr: print("OS error: {0}".format(err)) exceptValueError: print("Could not convert data to an integer.") except: print("Unexpected error:", sys.exc_info()[0]) raise
Else Clause • Follows all except clauses • Useful for code that needs to be executed if an exception does not come up in the try clause forarginsys.argv[1:]: try: f =open(arg, 'r') exceptIOError: print('cannot open', arg) else: print(arg, 'has', len(f.readlines()), 'lines') f.close()
Exception Argument • When an exception occurs it may have a value, known as the exception argument • The type of the argument depends on the exception type • After the except clause you can specify a variable after the exception name. This variable gets bound to instance.args
>>> try: ... raiseException('spam', 'eggs') ... exceptExceptionasinst: ... print(type(inst)) ... print(inst.args) ... print(inst) ... x, y =inst.args ... print('x =', x) ... print('y =', y) <class 'Exception'> ('spam', 'eggs') ('spam', 'eggs') x = spam y = eggs
Raising Exceptions • The raise statement allows a specific exception to be forced >>> raiseNameError('HiThere') Traceback(most recent call last): File "<stdin>", line 1, in ? NameError: HiThere
User Defined Exceptions • User defined exceptions can be named by creating a new exception class • Exceptions should be derived from the exception class
>>> classMyError(Exception): ... def__init__(self, value): ... self.value= value ... def__str__(self): ... returnrepr(self.value) ...>>> try: ... raiseMyError(2*2) ... exceptMyErroras e: ... print('My exception occurred, value:', e.value) ...My exception occurred, value: 4 >>> raiseMyError('oops!') Traceback (most recent call last): File "<stdin>", line 1, in ? __main__.MyError: 'oops!'
Defining Clean-up Actions0 • Try statements have an optional clause to define clean up actions >>> try: ... raiseKeyboardInterrupt ... finally: ... print('Goodbye, world!') ...Goodbye, world! KeyboardInterrupt • A finally statement is executed at the end of the try statement whether or not an exception occurred
Predefined Clean-up Actions • Some objects have standard clean-up actions to be executed when the object is no longer necessary, regardless of success forline inopen("myfile.txt"): print(line, end="") • This file will stay open for and indeterminate amount of time after the code has ran • With statement allows objects to be cleaned up after use withopen("myfile.txt") as f: for line in f: print(line, end="")