Exception

Exception handling allows developers to detect errors easily without writing special code to test return values. Even better, it lets us handle these errors in code that is nicely separated from the code that generated them. It also allows us to handle an entire class of errors with the same code, and lets a method defer the handling of its errors to the method that called it.

It is illegal to use a try clause without either a catch clause or a finally clause. A try clause by itself will result in a compiler error. Any catch clauses must immediately follow the try block. Any finally clauses must immediately follow the last catch clause. It is legal to omit either the catch cluase or the finally clause, but not both.

You can keep throwing an exception up through the methods. But what about when you get to the main() method at the top? It is actually possible to throw the exception out of main() as well. This results in the Java virtual machine (JVM) halting, and the stack trace will be printed to the output.

Be sure that if you catch both a subtype and a supertype of the same exception that the most specific type is caught first. If you don't, your program will not compile. When looking at exam questions, be sure to check that the question follows this rule.

When an object of type Exception is thrown, it must be caught. These objects are called checked exceptions. This does not include RuntimeException, which is an unchecked exception. 

All runtime exception derive from class RuntimeException and are unchecked exceptions. If an exception object does not subclass RuntimeException, it is a checked exception and must be either handled or specified.

When you override a method, you may not declare an exception type that is different from one delcared by the base method. You may, however, specify that the overridden method throws exception types that are subclass of those thrown by the base method. The overriding method may throw the same exceptions as the overridden method, it may throw as many exceptions as it wants as long as they are subclasses of the base-class exception, or it may throw no exceptions at all.

If you want to handle an exception in more than one handler, you can re-throw the exception. If you want to hide the details of the exception's true origin from the additional handlers, call the exception's fillInStackTrance() method. This will change the stack trace information in the exception so that the bottom of the trace is the current method. Rather than actually throwing the object returned by fillInStackTrance() as a Throwable, it's usually a better idea to cast it down to the Throwable subtype that it was when it was caught. For example:

improt java.io.*

public class Test{

  public void foo () throws IOException {

    try {

        new FileInputStream("nonexistent-file");

    }

    catch (IOException e) {

        throw (IOException) e.fillInStackTrace();

    }

  }

}

The finally keyword is used to define a block of code that is always executed after the catch clause or after the try clause if no exceptions occurred. This block is typically used to release resources and to perform any needed cleanup for the try clause. finally blocks are always executed and not required.

### Exception类介绍 在 Python 中,`Exception` 类是所有内置异常类的基类。当开发者需要处理各种异常情况时,`Exception` 类及其子类提供了一种结构化的方式来捕获和处理错误。除了使用 Python 内置的异常类型,开发者还可以自定义异常类型,通常是通过继承 `Exception` 类或者其他现有的异常类来实现。例如: ```python class MyCustomException(Exception): def __init__(self, message): self.message = message ``` 上述代码自定义了一个异常类型 `MyCustomException`,它继承自 `Exception` 类 [^1]。 ### Exception类使用方法 #### 捕获异常 在 Python 中,使用 `try-except` 语句来捕获和处理异常。以下是一个简单的示例,捕获 `ZeroDivisionError` 异常: ```python try: result = 1 / 0 except ZeroDivisionError as e: print(f"捕获到异常: {e}") ``` #### 自定义异常 自定义异常类通常通过继承 `Exception` 类来实现。下面是一个自定义异常类的示例: ```python class MyCustomException(Exception): def __init__(self, message): self.message = message try: raise MyCustomException("这是一个自定义异常") except MyCustomException as e: print(f"捕获到自定义异常: {e.message}") ``` #### 异常信息记录 可以将异常信息记录到文件中,以便后续分析。以下是一个将异常信息写入文件的示例: ```python import traceback try: print("step1") num = 1 / 0 except: with open("d:/a.txt", "a") as f: traceback.print_exc(file=f) ``` 上述代码使用 `traceback` 模块将异常信息写入指定文件 [^2]。 ### 相关知识 在处理异常时,还可以使用 `finally` 子句,无论是否发生异常,`finally` 子句中的代码都会执行。例如: ```python try: result = 1 / 0 except ZeroDivisionError as e: print(f"捕获到异常: {e}") finally: print("无论是否发生异常,这里的代码都会执行") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值