Handling Exceptions, and Multiple Handlers

0
12KB

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.

Suche
Kategorien
Mehr lesen
Technology
Web Design Tools and Technologies
Web Design Tools and Technologies Web design has evolved dramatically over the past few decades,...
Von ALAGAI AUGUSTEN 2024-07-26 17:47:49 0 23KB
Technology
Web Development Best Practices
Web Development Best Practices: A Comprehensive Guide Web development is an ever-evolving field,...
Von ALAGAI AUGUSTEN 2024-07-26 17:54:12 0 15KB
Technology
BASIC COMPUTER NETWORK
A computer network is a collection of interconnected devices, such as computers, servers, and...
Von ALAGAI AUGUSTEN 2024-07-17 17:26:52 0 9KB
Technology
COMPUTER NETWORKS
COMPUTER NETWORKS
Von Mpatswe Francis 2024-08-17 17:30:37 0 10KB
Talksphare https://talksphare.com