• 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 zeroat 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 filefis.close();} catch (IOException e) {e.printStackTrace();} finally {if (fis != null)try {fis.close();} catch (IOException e) {e.printStackTrace();}}}}
Java Try with Resources.Java Try with Resources中详细了解它。

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

Java try-catch示例相关推荐

  1. java 函数式编程 示例_功能Java示例 第1部分–从命令式到声明式

    java 函数式编程 示例 功能编程(FP)的目的是避免重新分配变量,避免可变的数据结构,避免状态并全程支持函数. 如果将功能性技术应用于日常Java代码,我们可以从FP中学到什么? 在这个名为&qu ...

  2. java 根据类名示例化类_如何使用示例从Java中的类路径加载资源

    java 根据类名示例化类 Java中的类路径不仅用于加载.class文件,而且还可以用于加载资源,例如属性文件,图像,图标,缩略图或任何二进制内容. Java提供了API来将这些资源读取为Input ...

  3. java 批量处理 示例_Java异常处理教程(包含示例和最佳实践)

    java 批量处理 示例 异常是可能在程序执行期间发生的错误事件,它会破坏其正常流程. Java提供了一种健壮且面向对象的方式来处理异常情况,称为Java异常处理 . 我们将在本教程中研究以下主题. ...

  4. 使用执行程序和ThreadPoolExecutor的Java线程池示例

    线程池管理工作线程池,它包含一个队列,使任务等待执行. 线程池管理可运行线程的集合,工作线程从队列中执行可运行线程. java.util.concurrent.Executors提供java.util ...

  5. Java并发– CyclicBarrier示例

    Java中的CyclicBarrier是JDK 5中java.util.Concurrent包中引入的同步器,以及其他并发实用程序(如Counting Semaphore , BlockingQueu ...

  6. Java EE 6示例– Galleria –第3部分

    关于Galleria示例的先前文章( 第1 部分 | 第2部分 | 第3部分 | 第4部分 )指导您完成基础知识以及对GlassFish和WebLogic的初始部署. 从今天开始,我尝试在其中添加一些 ...

  7. java 批量处理 示例_Java中异常处理的示例

    java 批量处理 示例 Here, we will analyse some exception handling codes, to better understand the concepts. ...

  8. java线程池示例_Java线程连接示例

    java线程池示例 Java Thread join method can be used to pause the current thread execution until unless the ...

  9. java反射用法示例_Java反射示例教程

    java反射用法示例 Java Reflection provides ability to inspect and modify the runtime behavior of applicatio ...

  10. Java GUI程序示例

    Java GUI程序示例 与命令行界面相比,图形界面对于用户来说更为简便易用.图形用户界面(Graphical User Interface,简称 GUI),关于Java图形用户界面,可参见 http ...

最新文章

  1. 表达式类型的实现_程序员如何使代码简洁,Lambda表达式入门之四大引用(下篇)...
  2. python待遇如何-Python薪资待遇到底是多少?老男孩python学习
  3. 面向对象第四单元(UML)总结体会课程总结
  4. C#创建https请求并使用pfx证书
  5. STM32——DMA
  6. 数学常用公式及规律、结论(二)
  7. python :super 的作用
  8. 怒爬某 Hub 资源就为撸了一个鉴黄平台
  9. Nginx(1)— Nginx工作原理
  10. mysql实现用拼音搜索中文的数据库实现
  11. 串口转WIFI模块通信
  12. 深圳立仪发布纳米级高分辨率光谱共焦位移传感器,精度再破纪录
  13. fine-grained prosody control专栏
  14. 【修复收藏功能、更新登录接口】知识付费小程序、博客小程序、完整版开源源码、资源变现小程序
  15. 【网页前端】HTML基本语法之排版标签和表单标签
  16. 一分钟让你知道Hadoop是什么
  17. 零数据分析实习经历如何秋招?
  18. 让洁净煤保障群众温暖过冬
  19. 13种最为荒谬的编程语言
  20. php面包屑导航实现思路,WordPress实现面包屑导航的方法

热门文章

  1. Elasticsearch之settings和mappings(图文详解)
  2. luogu P1892 团伙
  3. 高仿QQ顶部控件之IOS SegmentView
  4. mysql explain和profiling
  5. 背景图片,颜色变化脚本
  6. SIEMENS报到第一天
  7. [转载] python对列表单词排序_计算列表中单词的频率并按频率排序
  8. Enterprise Library 缓存应用程序块快速入门
  9. iOS 开发 - 绘制辉光效果
  10. myeclipse堆栈溢出