Java 中常见的 Exception 有哪些

news2024/10/6 12:27:16

Java 是一种广泛使用的编程语言,它的强大和流行程度在很大程度上归功于它的异常处理机制。异常是在程序执行期间出现的错误或意外情况。在 Java 中,异常是通过抛出和捕获异常对象来处理的。在本文中,我们将介绍 Java 中的一些常见异常类型及其使用方法。
在这里插入图片描述

文章目录

    • NullPointerException
    • ArrayIndexOutOfBoundsException
    • ClassCastException
    • ArithmeticException
    • IllegalArgumentException
    • FileNotFoundException
    • IOException
    • InterruptedException
    • NoSuchMethodException
    • OutOfMemoryError

NullPointerException

NullPointerException 是 Java 中最常见的异常之一。它通常表示试图访问 null 引用对象时发生的错误。例如,以下代码会抛出 NullPointerException 异常:

String str = null;
int length = str.length();

解决方法是在使用对象前先进行非空判断:

if (str != null) {
    int length = str.length();
}

ArrayIndexOutOfBoundsException

当访问数组时,如果使用了无效的索引,则会抛出 ArrayIndexOutOfBoundsException 异常。例如,以下代码会抛出异常:

int[] arr = new int[5];
int i = arr[5];

解决方法是确保在访问数组元素时使用的索引在有效范围内:

int[] arr = new int[5];
if (index < arr.length) {
    int i = arr[index];
}

ClassCastException

在 Java 中,如果尝试将一个对象强制转换为另一个不兼容的类型,则会抛出 ClassCastException 异常。例如,以下代码会抛出异常:

Object obj = new Integer(100);
String str = (String) obj;

解决方法是在进行类型转换之前进行类型检查:

Object obj = new Integer(100);
if (obj instanceof String) {
    String str = (String) obj;
}

ArithmeticException

如果在算术运算中出现了除以零的情况,则会抛出 ArithmeticException 异常。例如,以下代码会抛出异常:

int i = 1 / 0;

解决方法是在进行除法运算之前,先进行零判断:

if (divisor != 0) {
    int i = dividend / divisor;
}

IllegalArgumentException

如果传递给方法的参数不符合预期的条件,则会抛出 IllegalArgumentException 异常。例如,以下代码会抛出异常:

void printName(String name) {
    if (name == null || name.isEmpty()) {
        throw new IllegalArgumentException("Name cannot be empty");
    }
    System.out.println(name);
}

解决方法是在调用方法之前,确保传递的参数符合预期的条件:

String name = "John";
if (name != null && !name.isEmpty()) {
    printName(name);
}

FileNotFoundException

如果尝试打开不存在的文件,则会抛出 FileNotFoundException 异常。例如,以下代码会抛出异常:

File file = new File("nonexistent.txt");
Scanner scanner = new Scanner(file);

解决方法是确保文件存在并且路径正确:

File file = new File("existing.txt");
if (file.exists()) {
    Scanner scanner = new Scanner(file);
}

IOException

如果在进行输入输出操作时出现错误,则会抛出 IOException 异常。例如,以下代码会抛出异常:

try {
    InputStream input = new FileInputStream("file.txt");
    OutputStream output = new FileOutputStream("nonexistent.txt");
    byte[] buffer = new byte[1024];
    int length;
    while ((length = input.read(buffer)) > 0) {
        output.write(buffer, 0, length);
    }
} catch (IOException e) {
    e.printStackTrace();
}

解决方法是在进行输入输出操作时,使用 try-catch 块捕获异常:

try {
    InputStream input = new FileInputStream("file.txt");
    OutputStream output = new FileOutputStream("existing.txt");
    byte[] buffer = new byte[1024];
    int length;
    while ((length = input.read(buffer)) > 0) {
        output.write(buffer, 0, length);
    }
} catch (IOException e) {
    e.printStackTrace();
}

InterruptedException

如果在进行多线程编程时,线程被中断,则会抛出 InterruptedException 异常。例如,以下代码会抛出异常:

try {
    Thread.sleep(5000);
} catch (InterruptedException e) {
    e.printStackTrace();
}

解决方法是在进行线程操作时,使用 try-catch 块捕获异常:

try {
    Thread.sleep(5000);
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
}

NoSuchMethodException

如果调用了不存在的方法,则会抛出 NoSuchMethodException 异常。例如,以下代码会抛出异常:

class MyClass {
    public void method1() {
        System.out.println("Method 1");
    }
}

MyClass obj = new MyClass();
Method method2 = obj.getClass().getMethod("method2");

解决方法是确保调用的方法存在:

class MyClass {
    public void method1() {
        System.out.println("Method 1");
    }
}

MyClass obj = new MyClass();
try {
    Method method2 = obj.getClass().getMethod("method2");
} catch (NoSuchMethodException e) {
    e.printStackTrace();
}

OutOfMemoryError

如果程序试图分配过多的内存,则会抛出 OutOfMemoryError 异常。例如,以下代码会抛出异常:

List<Integer> list = new ArrayList<>();
while (true) {
    list.add(1);
}

解决方法是优化代码,减少内存使用量:

List<Integer> list = new ArrayList<>();
while (true) {
    try {
        list.add(1);
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        break;
    }
}

以上是 Java 中常见的异常类型及其解决方法。在实际编程中,我们还可能会遇到其他类型的异常。无论遇到哪种异常,我们都应该在代码中使用 try-catch 块捕获异常,并进行适当的处理,以保证程序的稳定性和可靠性。

附上完整代码和截图:

import java.io.*;
import java.lang.reflect.*;
import java.util.*;

public class ExceptionDemo {
    public static void main(String[] args) {
        // NullPointerException
        String str = null;
        try {
            int length = str.length();
        } catch (NullPointerException e) {
            e.printStackTrace();
        }

        // ArrayIndexOutOfBoundsException
        int[] arr = new int[5];
        int index = 5;
        try {
            int i = arr[index];
        } catch (ArrayIndexOutOfBoundsException e) {
            e.printStackTrace();
        }

        // ClassCastException
        Object obj = new Integer(100);
        try {
            String str2 = (String) obj;
        } catch (ClassCastException e) {
            e.printStackTrace();
        }

        // ArithmeticException
        int dividend = 1;
        int divisor = 0;
        try {
            int i = dividend / divisor;
        } catch (ArithmeticException e) {
            e.printStackTrace();
        }

        // IllegalArgumentException
        String name = "";
        try {
            printName(name);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }

        // FileNotFoundException
        File file = new File("nonexistent.txt");
        try {
            Scanner scanner = new Scanner(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        // IOException
        try {
            InputStream input = new FileInputStream("file.txt");
            OutputStream output = new FileOutputStream("existing.txt");
            byte[] buffer = new byte[1024];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // InterruptedException
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        // NoSuchMethodException
        MyClass obj2 = new MyClass();
        try {
            Method method2 = obj2.getClass().getMethod("method2");
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        // OutOfMemoryError
        List<Integer> list = new ArrayList<>();
        while (true) {
            try {
                list.add(1);
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
                break;
            }
        }
    }

    static class MyClass {
        public void method1() {
            System.out.println("Method 1");
        }
    }

    static void printName(String name) {
        if (name == null || name.isEmpty()) {
            throw new IllegalArgumentException("Name cannot be empty");
        }
        System.out.println(name);
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/479438.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

浅堆深堆解读

浅堆&#xff08;Shallow Heap&#xff09; 浅堆是指一个对象所消耗的内存。在32位系统中&#xff0c;一个对象引用会占据4个字节&#xff0c;一个int类型会占据4个字节&#xff0c;long型变量会占据8个字节&#xff0c;每个对象头需要占用8个字节。根据堆快照格式不同&#x…

【STM32】知识补充 深入探讨预分频器

【STM32】知识补充 深入探讨预分频器 概述分频器是什么工作原理计数器预分频器触发器预分频器模数计数器预分频器上升沿和下降沿 应用场景微控制器时钟预分频通信系统中的频率合成计时器与 PWM 波形生成数字电路设计中的同步与计时 预分频器实现方法硬件预分频器软件预分频器 案…

Swift之深入解析如何使用和自定义高级运算符

一、前言 在我之前的博客 Swift之深入解析如何自定义操作符 介绍了“基本运算符”&#xff0c;Swift 还提供了数种可以对数值进行复杂运算的高级运算符&#xff0c;它们包含了在 C 和 Objective-C 中已经被大家所熟知的位运算符和移位运算符。与 C 语言中的算术运算符不同&…

【flask】理解flask的几个难点,难啃的骨头,线程隔离啥的

1.三种路由和各自的比较 2.配置文件所有的字母必须大写 3.if __name__的作用 4.核心对象循环引用的几种解决方式–难 5.Flask的经典错误 6.上下文管理器 7.flask的多线程和线程隔离 三种路由 方法1&#xff1a;装饰器 python C#, java 都可以用这种方式 from flask import F…

SSM整合(三) | 异常处理器 - 项目异常的处理方案

文章目录 异常处理器异常处理器快速入门项目异常处理 异常处理器 异常处理器快速入门 程序开发过程中不可避免的会遇到异常现象 出现异常现象的常见位置与常见原因如下&#xff1a; 框架内部抛出的异常&#xff1a;因使用不规范导致 数据层抛出的异常&#xff1a;因外部服务器…

使用Statsmodel进行假设检验和线性回归

如果你使用 Python 处理数据&#xff0c;你可能听说过 statsmodel 库。Statsmodels 是一个 Python 模块&#xff0c;它提供各种统计模型和函数来探索、分析和可视化数据。该库广泛用于学术研究、金融和数据科学。在本文中&#xff0c;我们将介绍 statsmodel 库的基础知识、如何…

【技巧】Excel序号设置自动更新

做Excel表格的时候&#xff0c;我们经常需要设置序号&#xff0c;在输入序号的时候&#xff0c;你是不是这样做&#xff1f;手动输入序号1&#xff0c;再向下填充&#xff0c;当遇到有不想要的内容&#xff0c;点删除后&#xff0c;发现中间的序号就不连贯了&#xff0c;再手动…

二十五、OSPF高级技术——开销值、虚链路、邻居建立、LSA、多进程

文章目录 调试指令&#xff08;三张表&#xff09;1、邻居表&#xff1a;dis ospf peer brief2、拓扑表&#xff08;链路状态数据库&#xff09;&#xff1a;dis ospf lsdb3、路由表&#xff1a;dis ip routing-table 一、OSPF 开销值/度量值&#xff08;cost&#xff09;1、co…

代码审计笔记之开篇

思想 代码审计是从软件测试发展而来&#xff0c;早起一般采用常规软件测试与渗透测试的手段来发现源码漏洞&#xff0c;但是随着软件规模的越来越大&#xff0c;架构越来越复杂&#xff0c;安全漏洞和后门也越来越多越来越隐蔽&#xff0c;这使得传统的软件测试方法很难检出源…

【Java入门合集】第二章Java语言基础(一)

【Java入门合集】第二章Java语言基础&#xff08;一&#xff09; 博主&#xff1a;命运之光 专栏JAVA入门 学习目标 掌握变量、常量、表达式的概念&#xff0c;数据类型及变量的定义方法&#xff1b; 掌握常用运算符的使用&#xff1b; 掌握程序的顺序结构、选择结构和循环结构…

C/C++每日一练(20230501)

目录 1. 对链表进行插入排序 &#x1f31f;&#x1f31f; 2. 找出小于平均值的数 ※ 3. 二叉树的最大深度 &#x1f31f; &#x1f31f; 每日一练刷题专栏 &#x1f31f; Golang每日一练 专栏 Python每日一练 专栏 C/C每日一练 专栏 Java每日一练 专栏 1. 对链表进行…

【五一创作】Apollo(入门)

Apollo(入门) Quick Start 配置中心是一种统一管理各种应用配置的基础服务组件 Apollo&#xff08;阿波罗&#xff09;是携程框架部门研发的分布式配置中心&#xff0c;能够集中化管理应用不同环境、不同集群的配置&#xff0c;配置修改后能够实时推送到应用端&#xff0c;并且…

Springboot 实战一个依赖解决XSS攻击

1. 什么是XSS介绍 XSS: Cross Site Scripting&#xff0c;为不和层叠样式表(Cascading Style Sheets, CSS) 的缩写混淆&#xff0c;故将跨站脚本攻击缩写为XSS。 恶意攻击者往Web页面里插入恶意Script代码&#xff0c;当用户浏览该页之时&#xff0c;嵌入其中 Web里面的Scrip…

【高并发】并发数据结构与多核编程

系列综述&#xff1a; &#x1f49e;目的&#xff1a;本系列是个人整理为了秋招面试的&#xff0c;整理期间苛求每个知识点&#xff0c;平衡理解简易度与深入程度。 &#x1f970;来源&#xff1a;材料主要源于多处理器编程的艺术进行的&#xff0c;每个知识点的修正和深入主要…

【JavaEE初阶】认识线程(Thread)

目录 &#x1f33e; 前言 &#x1f33e; 了解线程 &#x1f308;1.1 线程是什么&#xff1f; &#x1f308;1.2 一些基本问题 &#x1f33e;2、创建线程的方式 &#x1f308; 2.1 继承Thread类 &#x1f308; 2.2 实现Runnable接口并重写run()方法 &#x1f308; 注意…

有哪些好的学习方法?学霸们自己在用,却不愿意透露的

临近期末,很多家长都在跟我咨询,怎么才能提升孩子的学习效率? 原因就是,每天看着自己的孩子学习到深夜,但不少内容还是记不住, 学习和复习的效果非常的不理想。 今天,给大家分享的方法,是我自己一直也都在用的方法,效果非常的棒。 学长Ron,江苏某省重点高中毕业,高…

给公司搭建一个人才库系统,前台(信息填写+简历上传)后台(筛选功能+下载简历)

首先指出目前代码的不足之处&#xff1a; 如果公司使用&#xff0c;代码还存在风险问题&#xff0c;需要增加防火墙、防PHP攻击、后台加验证等操作 以下指南&#xff1a; 1.Mod Security 和 Fail2Ban 是开源的安全软件&#xff0c;您可以在宝塔面板上安装和配置这些软件来增强您…

【JUC】ThreadLocal

【JUC】ThreadLocal 文章目录 【JUC】ThreadLocal1. 概述2. Thread、ThreadLocal、ThreadLocalMap 关系2.1 Thread 和 ThreadLocal2.2 ThreadLocal 和 ThreadLocalMap2.3 三者之间的关系 1. 概述 ThreadLocal 提供线程局部变量。这些变量与正常的变量不同&#xff0c;因为每一…

Java 基础入门篇(一)—— Java 概述

文章目录 一、Java 概述二、Java 的产品 JDK2.1 JDK 安装2.2 Java与 Javac 介绍2.3 Java 程序的开发步骤 三、Java 程序的执行原理四、JDK 的组成五、Java 的跨平台工作原理 一、Java 概述 Java 是 sun 公司在 1995 年推出的一门计算机高级编程语言&#xff0c;其语言风格接近人…

音视频技术开发周刊 | 291

每周一期&#xff0c;纵览音视频技术领域的干货。 新闻投稿&#xff1a;contributelivevideostack.com。 谷歌将 AI 芯片团队并入云计算部门 追赶微软和亚马逊 OpenAI推出的ChatGPT获得一定成功&#xff0c;微软是OpenAI的重要投资者&#xff0c;它将ChatGPT植入必应搜索&#…