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.

Αναζήτηση
Κατηγορίες
Διαβάζω περισσότερα
Business
How to Start Selling on Amazon FBA: A Step-by-Step Guide
Are you looking to tap into the booming world of e-commerce? Selling on Amazon using Fulfillment...
από Mpatswe Francis 2024-09-18 20:21:05 0 2χλμ.
Computer Programming
Bold Text in HTML
To make text bold in HTML, you can use either the <b> or <strong> element. Both...
από HTML PROGRAMMING LANGUAGE 2024-08-29 01:49:28 0 2χλμ.
Computer Programming
HTML Tables: A Comprehensive Guide with Code Examples
HTML tables are used to structure data in a tabular format, making it easy to read and...
από HTML PROGRAMMING LANGUAGE 2024-09-06 01:22:14 0 3χλμ.
Computer Programming
Floating-Point Numbers and Arithmetic Expressions
Floating-point numbers A floating-point number is a number with a decimal. Ex: 3.14,...
από Python for Everybody - Full University Python Course Code 2024-07-16 21:14:58 0 3χλμ.
Εκπαίδευση
SIMPLIFIED ECONOMICS
SIMPLIFIED ECONOMICS
από Landus Mumbere Expedito 2024-08-15 06:22:24 0 4χλμ.