Handling Exceptions, and Multiple Handlers

0
11χλμ.

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.

Αναζήτηση
Κατηγορίες
Διαβάζω περισσότερα
Εκπαίδευση
Reconstruction (Lecture)
Reconstruction Era (1865-1877) The Reconstruction Era was a period of immense change and...
από Modern American History 2024-07-19 05:37:05 0 8χλμ.
Εκπαίδευση
ECONOMICS MOCK
https://acrobat.adobe.com/id/urn:aaid:sc:EU:ec617028-2a6c-4082-b406-54df86b57b55
από Landus Mumbere Expedito 2024-07-24 19:44:22 0 8χλμ.
Computer Programming
Branching Basics and Multi-Branch Statements in Python
Branching is a fundamental concept in programming that allows your code to make decisions and...
από Python for Everybody - Full University Python Course Code 2024-07-16 21:42:09 0 8χλμ.
Chemistry
UTEB MOCK CHEMISTRY PAPER 1 2024
UTEB MOCK CHEMISTRY PAPER 1 2024
από Landus Mumbere Expedito 2024-08-03 15:32:50 0 10χλμ.
Technology
Importance of Cyber Laws
Cyber laws, also known as internet laws or digital laws, are essential for regulating activities...
από ALAGAI AUGUSTEN 2024-07-16 17:07:21 0 8χλμ.
Tebtalks https://tebtalks.com