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
Chemistry
UCE CHEMISTRY PAPER 1 KAMTEC MOCK 2024
UCE CHEMISTRY PAPER 1KAMTEC MOCK 2024
Par Expedito 2024-08-11 11:39:15 3 7KB
Technology
Understanding Web Frameworks and Libraries
Understanding Web Frameworks and Libraries In the world of web development, efficiency and...
Par Olaim 2024-07-26 17:50:40 0 12KB
Technology
Increasing Pressure on IT Experts
Information technology (IT) experts face increasing pressure due to several factors that have...
Par Olaim 2024-07-16 16:57:22 0 6KB
Technology
Scenarios of Computer Misuse and Their Effects on Society
Computer misuse can have widespread and serious impacts on society. It encompasses a wide range...
Par Olaim 2024-07-13 07:42:14 0 7KB
Technology
Computer Viruses
A computer virus is a type of malicious software (malware) designed to replicate itself and...
Par Olaim 2024-07-13 17:32:43 0 7KB
Tebtalks https://tebtalks.com