1 / 17

Python’s Errors and Exceptions

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 ')

asta
Download Presentation

Python’s Errors and Exceptions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Python’s Errors and Exceptions Nicholas Policelli

  2. Errors and Exceptions • There are two main types of errors: • Syntax Errors • Exceptions

  3. 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.

  4. 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

  5. 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

  6. 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 ?

  7. 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...") ...

  8. 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

  9. 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

  10. 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()

  11. 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

  12. >>> 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

  13. 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

  14. User Defined Exceptions • User defined exceptions can be named by creating a new exception class • Exceptions should be derived from the exception class

  15. >>> 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!'

  16. 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

  17. 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="")

More Related