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.

Căutare
Categorii
Citeste mai mult
Computer Programming
Programming basics
Computer programs are used by people every day. Everytime you use your smartphone, tablets, and...
Technology
Understanding the IF Function
step-by-step guide on using the IF function in Excel, incorporating best practices and addressing...
By Microsoft Excel 2024-09-03 03:12:25 0 3K
Technology
The VLOOKUP function in Excel
The VLOOKUP function in Excel is used to search for a value in the first column of a table and...
By Microsoft Excel Tips 2024-10-16 00:58:30 0 4K
Technology
HOW TO OVERCOME COMPUTER NETWORK CHALLENGES
Overcoming the challenges faced in managing and using computer networks requires a combination of...
By ALAGAI AUGUSTEN 2024-07-17 17:38:08 0 3K
Physics
QUANTUM PHYSICS
Quantum mechanics 
By PHYSICS FOR MASTER'S STUDENTS 2024-08-31 05:11:54 0 3K