Handling Exceptions, and Multiple Handlers

0
4Кб

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.

Поиск
Категории
Больше
Образование
The Compromise of 1877
The Compromise of 1877, also known as the Wormley Agreement, the Bargain of 1877, or the Corrupt...
От Modern American History 2024-07-19 05:48:55 0 3Кб
Technology
Increasing Pressure on IT Experts
Information technology (IT) experts face increasing pressure due to several factors that have...
От ALAGAI AUGUSTEN 2024-07-16 16:57:22 0 3Кб
Computer Programming
Setting up a text editor for HTML
Choosing a Text Editor The first step is to select a suitable text editor. There are numerous...
От HTML PROGRAMMING LANGUAGE 2024-08-13 03:18:39 0 2Кб
Mathematics
Understanding Quadratic Equations:
A quadratic equation is a polynomial equation of degree 2. It can be expressed in the general...
От Mpatswe Francis 2024-08-30 06:49:57 0 3Кб
Игры
कोलकाता फटाफट: एक गहन जानकारी
कोलकाता फटाफट: क्यों है खास?  कोलकाता फटाफट की खासियत इसकी सरलता और समय की पाबंदी है। यह...
От Karthik Bose 2024-12-17 12:05:26 0 570