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.

البحث
الأقسام
إقرأ المزيد
التعليم
S.4 CRE PRE-REGISTRATION 2024
https://acrobat.adobe.com/id/urn:aaid:sc:EU:21663e65-af20-41e8-b997-5def68c7399f
بواسطة Landus Mumbere Expedito 2024-07-19 23:19:32 0 3كيلو بايت
Business
Why Your Business Needs IT Services
Businesses often hesitate to hire IT services, considering them a high-cost investment. However,...
بواسطة ALAGAI AUGUSTEN 2024-07-19 14:20:20 0 5كيلو بايت
Technology
Management Information Systems (MIS)
Management Information Systems (MIS) are integrated systems designed to support management and...
بواسطة Business Information Systems (BIS) Course 2024-08-01 16:58:59 0 3كيلو بايت
التعليم
ECONOMICS MOCK
https://acrobat.adobe.com/id/urn:aaid:sc:EU:ec617028-2a6c-4082-b406-54df86b57b55
بواسطة Landus Mumbere Expedito 2024-07-24 19:44:22 0 3كيلو بايت
الألعاب
कोलकाता फटाफट: एक गहन जानकारी
कोलकाता फटाफट: क्यों है खास?  कोलकाता फटाफट की खासियत इसकी सरलता और समय की पाबंदी है। यह...
بواسطة Karthik Bose 2024-12-17 12:05:26 0 579