Java try-catch示例

  • Java try-catch block is used to handle exceptions in the program.

    Java try-catch块用于处理程序中的异常。
  • The code in the try block is executed and if any exception occurs, catch block is used to process them.

    执行try块中的代码,如果发生任何异常,则使用catch块对其进行处理。
  • If the catch block is not able to handle the exception, it’s thrown back to the caller program.

    如果catch块无法处理该异常,则将其返回给调用程序。
  • If the program is not able to process the exception, it’s thrown back to the JVM which terminates the program and prints the exception stack trace to the output stream.

    如果该程序无法处理该异常,则将其返回给JVM,该JVM终止该程序,并将异常堆栈跟踪信息打印到输出流。
  • A try block must be followed by either catch or finally block.

    尝试块之后必须是catch或finally块。

Java try-catch示例 (Java try-catch Example)

Let’s look at a simple code where we can get an exception.

让我们看一个简单的代码,从中可以得到一个异常。

package com.journaldev.examples;

public class JavaTryCatch {

	public static void main(String[] args) {
		System.out.println(divide(20,5));
		System.out.println(divide(20,0));
	}
	
	public static double divide(int x, int y) {
		return x/y;
	}

}

Output:

输出:

4.0
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at com.journaldev.examples.JavaTryCatch.divide(JavaTryCatch.java:11)
	at com.journaldev.examples.JavaTryCatch.main(JavaTryCatch.java:7)

Now let’s see how to use a try-catch block to handle the exception thrown by the divide() method.

现在,让我们看看如何使用try-catch块来处理 divide()方法引发的异常

package com.journaldev.examples;

public class JavaTryCatch {

	public static void main(String[] args) {
		try {
			System.out.println(divide(20, 5));
			System.out.println(divide(20, 0));
		} catch (ArithmeticException ae) {
			System.out.println(ae.getMessage());
		}
	}

	public static double divide(int x, int y) {
		return x / y;
	}

}

Output:

输出:

4.0
/ by zero

Java try-catch多个异常 (Java try-catch Multiple Exceptions)

We can catch multiple exceptions in a series of catch blocks. Let’s look at a simple example of using multiple catch blocks.

我们可以在一系列catch块中捕获多个异常。 让我们看一个使用多个catch块的简单示例。

package com.journaldev.examples;

public class JavaTryCatch {

	public static void main(String[] args) {

		try {
			foo(10);
		} catch (IllegalArgumentException ie) {
			System.out.println(ie.getMessage());
		} catch (NullPointerException ne) {
			System.out.println(ne.getMessage());
		}
	}

	public static void foo(int x) throws IllegalArgumentException, NullPointerException {
		// some code
	}

}

捕获例外命令 (Catching Exceptions Order)

Java Exceptions have a hierarchy. Throwable is the superclass of all the exceptions and errors. When catching multiple exceptions, the most specific Exception should be caught first. Otherwise, a compile-time error is thrown with the message as “Unreachable catch block. It is already handled by the catch block for Exception”.

Java异常具有层次结构。 Throwable是所有异常和错误的超类。 捕获多个异常时,应首先捕获最具体的异常。 否则,将引发编译时错误,并显示消息“ Unreachable catch block。 它已经由catch块处理为“例外”。

The below code will give compile time error because NullPointerException should be caught before Exception.

下面的代码将给出编译时错误,因为应该在Exception之前捕获NullPointerException。

try {
	foo(10);
} catch (Exception ie) {
	System.out.println(ie.getMessage());
} catch (NullPointerException ne) {
	System.out.println(ne.getMessage());
}

在单个catch块中捕获多个异常 (Catching Multiple Exceptions in a Single catch block)

If you notice the above code, we are printing the exception message in all the catch blocks. Java supports catching multiple exceptions in a single catch block. This feature was introduced in Java 7.

如果您注意到上面的代码,我们将在所有catch块中打印异常消息。 Java支持在单个catch块中捕获多个异常。 此功能是Java 7中引入的。

try {
	foo(10);
} catch (IllegalArgumentException | NullPointerException e) {
	System.out.println(e.getMessage());
}

Java try-catch-finally示例 (Java try-catch-finally Example)

The finally block is always executed, even if the program throws the exception and terminates. The finally block is generally used to make sure that the resources are closed before the program terminates.

即使程序引发异常并终止,finally块也始终执行。 通常使用finally块来确保在程序终止之前关闭资源。

Here is a real-life example of the try-catch-finally block. We are trying to open a file and process it. We are using finally block to make sure FileInputStream is closed.

这是try-catch-finally块的真实示例。 我们正在尝试打开文件并对其进行处理。 我们正在使用finally块来确保FileInputStream已关闭。

package com.journaldev.examples;

import java.io.FileInputStream;
import java.io.IOException;

public class JavaTryCatch {

	public static void main(String[] args) {
		FileInputStream fis = null;
		try {
			fis = new FileInputStream("data.txt");
			// code to process the file
			fis.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fis != null)
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}

	}

}

翻译自: https://www.journaldev.com/31136/java-try-catch-examples

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值