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.

Search
Categories
Read More
Technology
Understanding the Excel Interface
Excel's interface is designed to be user-friendly, but it can seem overwhelming at first. Let's...
By Microsoft Excel 2024-07-26 04:31:22 0 3K
Computer Programming
HTML forms
Here's a simple HTML form structure that includes a text input field, a submit button, and a...
By HTML PROGRAMMING LANGUAGE 2024-10-01 09:29:09 0 2K
Business
Why Your Business Needs IT Services
Businesses often hesitate to hire IT services, considering them a high-cost investment. However,...
By ALAGAI AUGUSTEN 2024-07-19 14:20:20 0 5K
Chemistry
UTEB MOCK CHEMISTRY PAPER 1 2024
UTEB MOCK CHEMISTRY PAPER 1 2024
By Landus Mumbere Expedito 2024-08-03 15:32:50 0 3K
Health
The Ultimate User's Manual for Vidalista 20mg
Vidalista 20mg and Vidalista 60mg are two popular medications for treating erectile dysfunction...
By Norah Simon 2024-09-10 11:10:53 0 3K