Home Backend Development Python Tutorial A brief discussion on Python throwing exceptions, custom exceptions, and passing exceptions

A brief discussion on Python throwing exceptions, custom exceptions, and passing exceptions

Jul 21, 2016 pm 02:53 PM
Custom exception

1. Throw exception

Python uses exception objects to represent abnormal situations. When an error is encountered, an exception will be thrown. If the exception object is not handled or caught, the program will terminate execution with a so-called traceback (an error message).

raise statement

The raise keyword in Python is used to raise an exception, which is basically the same as the throw keyword in C# and Java, as shown below:

import traceback

def throw_error():
  raise Exception("抛出一个异常")#异常被抛出,print函数无法执行
  print("飞天猪")
  
throw_error()

Copy after login

#Run result:

'''Traceback (most recent call last):
 File "C:\Users\Administrator\Desktop\systray.py", line 7, in <module>
  throw_error()
 File "C:\Users\Administrator\Desktop\systray.py", line 4, in throw_error
  raise Exception("抛出一个异常")#异常被抛出,print函数无法执行
Exception: 抛出一个异常'''
Copy after login

After the raise keyword, the throw is a general exception type (Exception). Generally speaking, the more detailed the exception thrown, the better

2. Transmission exception:

If you catch an exception, but want to re-raise it (pass the exception), you can use the raise statement without parameters:

class MufCalc(object):
  m = False
  def calc(self,exp):
    try:
      return eval(exp)
    except ZeroDivisionError:
      if self.m:
        print("cool")
      else:
        raise

app = MufCalc()
app.calc(2/0)

Copy after login

3. Custom exception type :

You can also customize your own special types of exceptions in Python, just inherit from the Exception class (directly or indirectly):

class MyError(Exception):
  pass
Copy after login

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1658
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
How to implement error handling and custom exceptions in FastAPI How to implement error handling and custom exceptions in FastAPI Jul 29, 2023 pm 07:00 PM

How to implement error handling and custom exceptions in FastAPI Introduction: FastAPI is a modern web framework based on Python. Its high performance and rapid development capabilities make it increasingly popular in the development field. In actual applications, errors and exceptions are often encountered. This article will introduce how to implement error handling and custom exceptions in FastAPI to help developers better handle and manage error situations in applications. FastAPI error handling: FastAPI provides a

Creation and use of Java custom exceptions Creation and use of Java custom exceptions May 03, 2024 pm 10:27 PM

Custom exceptions are used to create error messages and handling logic. First, you need to inherit Exception or RuntimeException to create a custom exception class. Then, you can override the getMessage() method to set the exception message. Exceptions are thrown through the throw keyword. Use try-catch blocks to handle custom exceptions. This article provides a practical case for parsing integer input and throwing a custom InvalidInputException when the input is not an integer.

How to create custom exception handler in CakePHP? How to create custom exception handler in CakePHP? Jun 03, 2023 pm 11:01 PM

CakePHP is a popular PHP framework that allows you to quickly build web applications. Various exceptions can occur while processing user input and performing tasks such as database operations. How can exceptions be handled so that an error message is not presented directly to the user when a problem occurs? This is where custom exception handlers come in. In this article, we will explore how to create custom exception handlers in CakePHP. Why do we need custom exception handlers? When a web application throws an exception, Cak

Python exception handling: master the sharp edge and control your code life Python exception handling: master the sharp edge and control your code life Feb 25, 2024 pm 04:10 PM

Python is a powerful programming language, but it's not perfect. When running a Python program, you may encounter a variety of exceptions, causing the program to crash or produce erroneous results. In order to avoid these situations from happening, we need to handle abnormal situations, that is, exception handling. The basic syntax for exception handling is try-except-finally. The try block contains code that may cause an exception, the except block is used to catch exceptions, and the finally block is used for code that will be executed regardless of whether an exception occurs. The following is a simple exception handling example: try: #Code that may cause exceptions exceptExceptionase: #Catch exceptions and handle fi

C++ program creates custom exception C++ program creates custom exception Aug 26, 2023 pm 07:53 PM

Exceptions are a very core concept of C++. Exceptions occur when an undesired or impossible operation occurs during execution. Handling these unwanted or impossible operations in C++ is called exception handling. Exception handling mainly uses three specific keywords, which are ‘try’, ‘catch’ and ‘throw’. The ‘try’ keyword is used to execute code that may encounter exceptions, the ‘catch’ keyword is used to handle these exceptions, and the ‘throws’ keyword is used to create exceptions. Exceptions in C++ can be divided into two types, namely STL exceptions and user-defined exceptions. In this article, we focus on how to create these custom exceptions. More details on exception handling can be found here. Use a single

Solution to Java custom exception handling exception (CustomExceptionHandlerException) Solution to Java custom exception handling exception (CustomExceptionHandlerException) Aug 17, 2023 pm 06:18 PM

Solution to Java custom exception handling exception (CustomExceptionHandlerException) In Java development, we often encounter various abnormal situations. In addition to the exception types already defined in Java, we can also customize exception types to better handle specific business logic. However, in the process of using custom exception handling, you sometimes encounter some problems, such as CustomExceptionHandlerExcept

How to customize exceptions in Java? How to customize exceptions in Java? Apr 12, 2024 am 09:06 AM

Creating custom exceptions in Java improves application robustness. It requires: Create a custom exception class, inherited from Exception or RuntimeException. Throws a custom exception, similar to throwing a regular exception. Catch custom exceptions when calling methods for more informative error messages.

How to catch and handle custom exceptions in PHP? How to catch and handle custom exceptions in PHP? May 09, 2024 pm 10:00 PM

How to catch and handle custom exceptions in PHP: Inherit the Exception class to create custom exceptions. Use the throw keyword to throw a custom exception. Use try, catch, and finally blocks to catch and handle exceptions.

See all articles