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.

Site içinde arama yapın
Kategoriler
Read More
Other
Clear the Clutter
 A Word of Encouragement Life is a journey filled with ups and downs, triumphs and...
By Olaim 2024-08-10 12:44:57 0 5K
Politics
Putin in Mongolia, no arrest made - ablow to ICC
Russian President Vladimir Putin recently visited Mongolia, marking his first trip to a member...
By Patswe 2024-09-03 20:32:28 0 5K
EĞİTİM BİLGİLERİ
ECONOMICS DISCUSSION QUESTIONS
ECONOMICS DISCUSSION QUESTIONS
By Question Bank 2024-08-26 05:07:49 0 6K
Computer Programming
Variables, Assignments, and Identifiers
Variables Variables are used to store data that can be used and manipulated throughout...
Computer Programming
Basic structure of an HTML document
An HTML document is composed of two main sections: the head and the body. The <head>...
By HTML PROGRAMMING LANGUAGE 2024-08-13 03:25:34 0 5K