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.

Rechercher
Catégories
Lire la suite
Autre
Know Your Worth, Control Your Emotions, and Never Settle
In a world that often pushes us to conform, understanding your value, mastering your emotions,...
Par ALAGAI AUGUSTEN 2024-08-14 05:42:34 0 9KB
Éducation
P.5 AND P.6 SCIENCE REVISION
P.5 AND P.6 SCIENCE REVISION
Par Landus Mumbere Expedito 2024-08-04 10:33:50 0 10KB
Wellness
Choosing Kindness in the Face of Anger: A Path to Transformation
Imagine standing at the crossroads of an emotional storm. Someone’s words or actions have...
Par ALAGAI AUGUSTEN 2024-12-18 16:55:54 0 12KB
Technology
Ethics of Using Computers Between People
The use of computers and digital technology in interactions between people raises numerous...
Par ALAGAI AUGUSTEN 2024-07-13 07:16:31 0 10KB
Computer Programming
HTML Table Colspan & Rowspan
HTML Table Colspan and Rowspan Colspan and rowspan are attributes used to merge cells in a...
Par HTML PROGRAMMING LANGUAGE 2024-09-06 01:36:07 0 11KB
Tebtalks https://tebtalks.com