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.

Pesquisar
Categorias
Leia Mais
Technology
HTML - The Structure of Web Pages
HTML, or HyperText Markup Language, is the standard language used to create and design web pages....
Por Olaim 2024-07-25 19:30:38 0 12K
Educação
PROJECT WORK UNDER THE NLSC
https://acrobat.adobe.com/id/urn:aaid:sc:EU:f40101ab-c7b1-4329-a7bd-e5b826cba07a
Por Expedito 2024-07-20 21:29:58 0 7K
Technology
Creating a login form using HTML and CSS
Creating a login form using HTML and CSS is a fundamental skill in web development. Here's a...
Por tebtalks 2025-01-21 01:24:55 0 7K
Physics
COLLECTION OF PHYSICS SCENARIOS
COLLECTION OF PHYSICS SCENARIOS
Por Expedito 2024-08-13 19:19:44 0 8K
Physics
UCE PHYSICS SEMINAR QUESTIONS
UCE PHYSICS SEMINAR QUESTIONS
Por Expedito 2024-08-04 06:02:18 0 9K
Tebtalks https://tebtalks.com