在Java中,try-catch语句用于处理可能会抛出异常的代码。当你预计某段代码可能会导致异常时,应该将其放在try块中。如果try块中的代码抛出了异常,程序会立即跳转到相应的catch块来处理异常。以下是try-catch语句的基本结构:
try { // 可能会抛出异常的代码 } catch (ExceptionType1 e) { // 处理ExceptionType1类型的异常 } catch (ExceptionType2 e) { // 处理ExceptionType2类型的异常 } finally { // 无论是否发生异常,都会执行这里的代码(可选) } 其中,ExceptionType1和ExceptionType2是你希望捕获的异常类型,例如IOException、NullPointerException等。e是一个异常对象,包含了异常的详细信息。
以下是一个简单的示例:
public class TryCatchExample { public static void main(String[] args) { try { int result = divide(10, 0); System.out.println("Result: " + result); } catch (ArithmeticException e) { System.err.println("Error: " + e.getMessage()); } finally { System.out.println("Division operation completed."); } } public static int divide(int a, int b) throws ArithmeticException { return a / b; } } 在这个示例中,我们尝试将10除以0,这会导致ArithmeticException异常。try块中的代码会抛出异常,然后跳转到catch块来处理异常。最后,finally块中的代码会被执行。