Catch any error in Python

前端 未结 8 1657
一个人的身影
一个人的身影 2021-02-01 14:24

Is it possible to catch any error in Python? I don\'t care what the specific exceptions will be, because all of them will have the same fallback.

相关标签:
8条回答
  • 2021-02-01 15:21
    try:
        # do something
    except Exception, e:
        # handle it
    

    For Python 3.x:

    try:
        # do something
    except Exception as e:
        # handle it
    
    0 讨论(0)
  • 2021-02-01 15:26

    Built-In Exceptions in Python

    Built-In exception classes are divided into Base error classes from which the error classes are defined and Concrete error classes which define exceptions which you are more likely to see time to time.

    The more detailed document about the buit-In exception can be found in [https://docs.python.org/3/library/exceptions.html]

    Custom Exceptions

    It is used to fit your specific application situation. For example, you can create your own exception as RecipeNotValidError as the recipe is not valid in your class for developing a cooking app.

    Implementation

    
    class RecipeNotValidError(Exception):    
        def __init__(self):       
            self.message = "Your recipe is not valid"        
            try:            
                raise RecipeNotValidError
            except RecipeNotValidError as e:            
                print(e.message)
    
    

    These are custom exceptions that are not defined in the standard library. The steps you can follow to create custom classes are :

    1. Subclass the Exception class.
    2. Create a new Exception class of your choice.
    3. Write your code and use the try...except flow to capture and handle your custom exception.
    0 讨论(0)
提交回复
热议问题