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.

Buscar
Categorías
Read More
Juegos
Nulls Brawl Download With All Fighters Open and New Stuff Like Lumi
So here’s the thing, Brawl Stars is good and all, but sometimes it gets tiring when you...
By wamuu 2025-04-14 13:55:53 0 3K
Technology
COMPONENTS OF A LAN
A Local Area Network (LAN) is a network that connects computers and other devices within a...
By Olaim 2024-07-17 17:45:57 0 6K
Technology
Decision Support Systems (DSS)
Decision Support Systems (DSS) are computerized information systems designed to assist in...
By Business Information Systems (BIS) Course 2024-08-01 17:00:08 0 6K
Computer Programming
Handling Exceptions, and Multiple Handlers
Handling Exceptions with try-except An exception is an event that disrupts the normal...
Technology
Versions of the Linux Operating System
Linux is a versatile and open-source operating system kernel that serves as the foundation for a...
By tebtalks 2024-07-13 07:17:35 0 6K
Tebtalks https://tebtalks.com