Handling Exceptions, and Multiple Handlers

0
13χλμ.

Handling Exceptions with try-except

An exception is an event that disrupts the normal flow of your Python program. Some examples:

  • KeyError – raised when a key is not found in a dictionary
  • IndexError - raised when you try to access an element outside the range of the list

Exception handling is error-checking code in your program that looks for a special circumstance. Exception handling is done with try-except blocks of code.

  • try – the block of code where something could go wrong (may throw an exception)
  • except – the code to run if an exception happens

Multiple exception handlers

If more than one type of exception may be raised in a try block, then you can have multiple exception handlers by adding more except blocks of code to handle each one.

An unhandled exception happens if no exception handler exists.

Raising exceptions

If you have code written that detects an error, execute a raise statement to exit the try block and start executing the except block. Example: raise ValueError(’Invalid number’) creates a new exception of type ValueError, and the string argument explains the error.

Use the as keyword to provide an object for your exception.

Αναζήτηση
Κατηγορίες
Διαβάζω περισσότερα
Business
Build Meaningful Connections and Watch Your Business Thrive
Networking is Key! Build Meaningful Connections and Watch Your Business Thrive In the fast-paced...
από ALAGAI AUGUSTEN 2024-07-23 17:42:22 0 19χλμ.
Technology
Financial Theft
Financial Theft involves the unlawful acquisition of money, assets, or financial information...
από ALAGAI AUGUSTEN 2024-07-13 17:26:52 0 12χλμ.
Εκπαίδευση
A MUST KNOW FOR S6 HISTORY STUDENTS
https://acrobat.adobe.com/id/urn:aaid:sc:EU:8ec647ff-c6ae-4844-831f-3f6e719e9bb0
από Landus Mumbere Expedito 2024-07-15 19:59:30 0 15χλμ.
Biology
CBTI UCE BIOLOGY MOCK EXAM PAPER 1
CBTI UCE BIOLOGY MOCK EXAM PAPER 1
από Landus Mumbere Expedito 2024-07-30 12:40:47 0 11χλμ.
Εκπαίδευση
Unlock Your Potential with Lifelong Learning
In today’s fast-paced, ever-changing world, the concept of lifelong learning has become...
από ALAGAI AUGUSTEN 2024-07-21 19:03:27 0 16χλμ.
Talksphare https://talksphare.com