Handling Exceptions, and Multiple Handlers

0
9Кб

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.

Поиск
Категории
Больше
Computer Programming
Element-specific attributes (alt for images, href for links)
While global attributes can be applied to any HTML element, some attributes are specific to...
От HTML PROGRAMMING LANGUAGE 2024-08-15 01:47:04 0 7Кб
Physics
UCE PHYSICS PAPER 1 WAKATA MOCKS 2024
UCE PHYSICS PAPER 1 WAKATA MOCKS 2024
От Landus Mumbere Expedito 2024-08-10 07:19:10 0 10Кб
Biology
CAPILLARITY
How does capillary action work in plants? Capillary action in plants works through the...
От Okiliong Peter 2024-09-04 13:04:49 0 14Кб
Technology
Understanding Brute Force Attacks
A brute force attack is a method used by attackers to gain unauthorized access to a system,...
От ALAGAI AUGUSTEN 2024-07-15 06:43:17 0 8Кб
Tebtalks https://tebtalks.com