9.8.3 Catching Multiple Exceptions in One except Clause

  • If several except suites are identical, you can catch those exception types by specifying them as a tuple in a single except handler:
    except (type1, type2, ) as variable_name:
    
  • as clause is optional
    • Typically, programs do not need to reference the caught exception object directly
    • Can use the variable in the as clause to reference the exception object in the except suite

9.8.4 What Exceptions Does a Function or Method Raise?

  • Before using any function or method, read its online API documentation
    • Specifies what exceptions are thrown (if any) by the function or method
    • Indicates reasons why such exceptions may occur
  • Next, read the online API documentation for each exception type to see potential reasons why such an exception occurs

9.8.5 What Code Should Be Placed in a try Suite?

  • For proper exception-handling granularity, each try statement should enclose a section of code small enough that, when an exception occurs, the specific context is known and the except handlers can process the exception properly
  • If many statements in a try suite raise the same exception types, multiple try statements may be required to determine each exception’s context

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.