Manually raising (throwing) an exception in Python

转自Manually raising (throwing) an exception in Python

def demo_bad_catch():  # Avoid raising a generic Exception
    try:
        raise ValueError('Represents a hidden bug, do not catch this')
        raise Exception('This is the exception you expect to handle')
    except Exception as error:
        print('Caught this error: ' + repr(error))

>demo_bad_catch()
>Caught this error: ValueError('Represents a hidden bug, do not catch this',)
def demo_no_catch(): # more specific catches won't catch the general exception:
    try:
        raise Exception('general exceptions not caught by specific handling')
    except ValueError as e:
        print('we will not catch exception: Exception')
>demo_no_catch()
>Exception                                 Traceback (most recent call last)
<ipython-input-4-ec39b7ba8683> in <module>()
----> 1 demo_no_catch()

<ipython-input-3-c6f2d59e41ed> in demo_no_catch()
      1 def demo_no_catch():
      2     try:
----> 3         raise Exception('general exceptions not caught by specific handling')
      4     except ValueError as e:
      5         print('we will not catch exception: Exception')

Exception: general exceptions not caught by specific handling
try:
    raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz') 
except ValueError as err:
    print(err.args)
> ('A very specific bad thing happened', 'foo', 'bar', 'baz')
try:
    raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz') 
except ValueError as err:
    raise
> ValueError                                Traceback (most recent call last)
<ipython-input-6-d323cf99e315> in <module>()
      1 try:
----> 2     raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz')
      3 except ValueError as err:
      4     raise

ValueError: ('A very specific bad thing happened', 'foo', 'bar', 'baz')

  • Exception hierarchy
BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      |    +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning
手动安装Python 3.12.3通常涉及以下几个步骤: 1. **下载安装包**: - 访问Python官方网站(https://www.python.org/downloads/),找到“Downloads”部分,选择对应平台(如Windows、Linux或macOS)的Python 3.12.3版本的源码文件(一般名为`python-3.12.3.tgz`或`python-3.12.3-amd64.exe`等)。 2. **解压文件**: - 如果下载的是.tar.gz文件,使用命令行(如在Linux/Mac): ``` tar xvf python-3.12.3.tgz ``` - 如果是Windows,可以右键点击并选择“提取所有”。 3. **配置和编译**: - 进入解压后的目录,例如`python-3.12.3`,运行`configure`命令来生成编译选项,然后使用`make`进行编译。对于Unix-like系统: ``` ./configure make ``` - 对于Windows,通常会有`config.bat`或`setup.py`脚本来帮助完成这个过程。 4. **安装Python**: - 编译完成后,运行`sudo make install`(Unix-like系统,可能需要管理员权限)或`python setup.py install`(Windows)来将Python安装到系统中指定位置。 5. **添加环境变量**: - 完成安装后,需要更新系统的环境变量路径,让操作系统知道在哪里找到Python解释器。具体操作依赖于你的操作系统(例如,在Linux Mint或Ubuntu上,可以在`~/.bashrc`或`~/.profile`中添加`export PATH=$PATH:/path/to/python/installation/bin`)。 6. **验证安装**: - 最后,打开终端或命令提示符,输入`python3`或`python`(取决于你的设置),如果看到Python的欢迎消息,则说明安装成功。 记得根据你的操作系统和需求调整上述步骤。如果你首次接触这种操作,建议查阅官方文档或在线教程以获取更详细的指导。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值