try-catch怎么在java中使用

2023-05-18,

本篇文章给大家分享的是有关try-catch怎么在java中使用,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

Java的特点有哪些

Java的特点有哪些
1.Java语言作为静态面向对象编程语言的代表,实现了面向对象理论,允许程序员以优雅的思维方式进行复杂的编程。
2.Java具有简单性、面向对象、分布式、安全性、平台独立与可移植性、动态性等特点。
3.使用Java可以编写桌面应用程序、Web应用程序、分布式系统和嵌入式系统应用程序等。

1.try和catch概念

try -- 用于监听。将要被监听的代码(可能抛出异常的代码)放在try语句块之内,当try语句块内发生异常时,异常就被抛出。

catch -- 用于捕获异常。catch用来捕获try语句块中发生的异常。

2.try和catch用法

public class Demo1 {
 
    public static void main(String[] args) {
        try {
            int i = 10/0;
              System.out.println("i="+i); 
        } catch (ArithmeticException e) {
              System.out.println("Caught Exception"); 
            System.out.println("e.getMessage(): " + e.getMessage()); 
            System.out.println("e.toString(): " + e.toString()); 
            System.out.println("e.printStackTrace():");
            e.printStackTrace(); 
        }
    }
}

在try语句块中有除数为0的操作,该操作会抛出java.lang.ArithmeticException异常。通过catch,对该异常进行捕获。

3.try-catch处理异常

private static void readFile(String filePath) {
File file = new File(filePath);
String result;
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(file));
while((result = reader.readLine())!=null) {
System.out.println(result);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}}

以上就是try-catch怎么在java中使用,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注本站行业资讯频道。

《try-catch怎么在java中使用.doc》

下载本文的Word格式文档,以方便收藏与打印。