Handling Exceptions, and Multiple Handlers

0
10كيلو بايت

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.

البحث
الأقسام
إقرأ المزيد
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 9كيلو بايت
أخرى
10 ways to show love
Here are 10 meaningful ways to show love:Quality Time – Spend uninterrupted, focused time...
بواسطة Tebtalks Access 2024-09-23 04:45:26 1 9كيلو بايت
Computer Programming
HTML Table Sizes: Controlling Dimensions
HTML tables can be sized using the width and height attributes, which specify the dimensions of...
بواسطة HTML PROGRAMMING LANGUAGE 2024-09-06 01:29:20 0 10كيلو بايت
Biology
S 4 BIOLOGY INTERNAL MOCK 2024
https://acrobat.adobe.com/id/urn:aaid:sc:EU:7df0e01a-f4c6-457b-9167-b4f4a4726315
بواسطة Landus Mumbere Expedito 2024-07-19 23:23:38 0 9كيلو بايت
Chemistry
MARKING GUIDE FOR UMTA UCE CHEMISTRY PAPER 1 2024
MARKING GUIDE FOR UMTA UCE CHEMISTRY PAPER 1 2024
بواسطة Landus Mumbere Expedito 2024-08-19 20:56:42 0 10كيلو بايت
Tebtalks https://tebtalks.com