Handling Exceptions, and Multiple Handlers

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.

Cerca
Categorie
Leggi tutto
Formazione
The Battle of Little Bighorn
By Modern American History 2024-08-02 16:27:20 0 6K
Health
Understanding Over/Under Penalty Betting and Proven Tips for Success
Understanding Over/Under Penalty Betting and Proven Tips for Success To make a football match...
By wintips123 2025-01-17 07:16:14 0 4K
Physics
MATIGO PHYSICS PAPER 1 2024
MATIGO UACE PHYSICS PAPER 1 2024
By Question Bank 2024-09-05 17:26:27 0 7K
Altre informazioni
Aligning Your Energy with Your Dreams: The Path to Manifestation
In a world where personal development and spiritual growth have gained prominence, the concept of...
By Olaim 2024-08-18 08:18:34 1 7K
Technology
Licensing Linux
Linux is an open-source operating system kernel, and its licensing is a crucial aspect of its...
By tebtalks 2024-07-13 07:21:57 0 5K