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.

Pesquisar
Categorias
Leia mais
Technology
Forms of Computer Software Attacks
Computer software attacks are malicious activities aimed at compromising the security, integrity,...
Por ALAGAI AUGUSTEN 2024-07-13 17:30:11 0 9KB
Educação
SIMPLIFIED ECONOMICS
SIMPLIFIED ECONOMICS
Por Landus Mumbere Expedito 2024-08-15 06:22:24 0 15KB
Music
How to Get YouTube Premium for Free?
Using YouTube Vanced: The Popular Alternative YouTube Vanced has emerged as one of the most...
Por Vanced32 Vanced32 2025-03-17 13:55:13 0 15KB
Chemistry
UACE WAKISSHA CHEMISTRY PAPER 2 2024
UACE WAKISSHA CHEMISTRY PAPER 2 2024
Por Landus Mumbere Expedito 2024-08-03 09:07:58 0 10KB
Educação
The New South & Trans-Mississippi West
The New South and Trans-Mississippi West were both regions undergoing significant change...
Por Modern American History 2024-07-19 05:59:31 0 8KB
Tebtalks https://tebtalks.com