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
Computer Programming
HTML Table Colgroup
HTML Table Colgroup The colgroup element in HTML is used to group columns within a table. It...
By HTML PROGRAMMING LANGUAGE 2024-09-06 01:44:20 0 2K
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...
Education
S.4 PHYSICAL EDUCATION MOCK EXAM
https://acrobat.adobe.com/id/urn:aaid:sc:EU:ec617028-2a6c-4082-b406-54df86b57b55
By Landus Mumbere Expedito 2024-07-24 19:32:08 0 3K
Technology
Understanding the MOD Function
The MOD function in Excel is used to find the remainder after a number is divided by a divisor....
By Microsoft Excel 2024-09-03 03:27:42 2 2K
Technology
Overview of navigation and basic spreadsheet terminology
Navigation in Spreadsheets: Opening a Spreadsheet: To open a spreadsheet, click on the...
By Microsoft Excel 2024-07-26 04:39:53 0 2K