专注Java教育14年 全国咨询/投诉热线:444-1124-454
赢咖4LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 Java学习 Java异常类型汇总

Java异常类型汇总

更新时间:2022-11-17 12:02:57 来源:赢咖4 浏览694次

Java是一种面向对象的编程语言。它提供对异常处理等各种机制的支持。Java 的这一特性使开发人员能够管理由异常引起的运行时错误。

在本文中,您将了解Java中的异常。您还将了解Java 中不同类型的异常。

Java异常是限制程序正常执行的不需要的错误或错误或事件。每次发生异常时,程序执行都会中断。屏幕上显示一条错误消息。

异常的发生背后有几个原因。这些是发生异常的一些情况:

每当用户提供无效数据时。

请求访问的文件在系统中不存在。

当Java 虚拟机(JVM) 内存不足时。

网络在通信过程中掉线。

现在让我们探索 Java 中不同类型的异常。

所有异常类的父类都是java.lang.Exception类。图 1 说明了不同类型的 Java 异常。

如果我们谈论Exception类,它是内置Throwable类的子类。还有另一个从 Throwable 类派生的子类,即Error,如图 1 所示。错误可以定义为一种异常情况,表明程序的执行出现了问题。这些不是由 Java 程序处理的。

Throwable类中有一些重要的方法可用,如下所示:

public String getMessage() – 提供有关通过消息发生的异常的信息,该消息在Throwable 构造函数中初始化。

public Throwable getCause() – 提供由Throwable 对象表示的异常的根本原因。

public void printStackTrace() – 用于显示toString()的输出以及到System.err(错误输出流)的堆栈跟踪。

public StackTraceElement [] getStackTrace() – 返回一个数组,其中包含堆栈跟踪中存在的每个元素。索引 0 元素将象征调用堆栈的顶部,数组的最后一个元素将标识调用堆栈的底部。

Java中主要有以下两种类型的异常:

检查异常

未经检查的异常

检查异常

检查异常也称为编译时异常,因为这些异常在编译过程中由编译器检查,以确认程序员是否处理了异常。如果不是,则系统显示编译错误。例如,SQLException、IOException、InvocationTargetException和ClassNotFoundException。

为了说明检查异常的概念,让我们考虑以下代码片段:

import java.io.*;
class demo1 {
    public static void main(String args[]) {
        FileInputStream input1 = null;
        /* FileInputStream(File filename) is a constructor that will throw
         *     FileNotFoundException (a checked exception) 
         */
        input1 = new FileInputStream("D:/file.txt");
        int m;
        // The read() of FileInputStream will also throw a checked exception
        while(( m = input1.read() ) != -1) {
            System.out.print((char)m);
        }
        // The close() will close the file input stream, and it will also throw a exception
        input1.close();
    }
}

输出

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Unhandled exception type FileNotFoundException
Unhandled exception type IOException
Unhandled exception type IOException

抛出关键字

输出中清楚地显示程序在编译过程中抛出异常。有两种方法可以解决此类问题。您可以在throw关键字的帮助下声明异常。

import java.io.*;
class demo1 {
    public static void main(String args[]) throws IOException {
        FileInputStream input1 = null;
        input1 = new FileInputStream("D:/file.txt");

        int m;
        while ((m = input1.read()) != -1) {
            System.out.print((char)m);
        }
        input1.close();
    }
}

输出:文件将显示在屏幕上。

try-catch 块

除了上述方法外,还有一种解决异常的方法。您可以在try-catch 块的帮助下管理它们。

import java.io.*;
class demo1 {
    public static void main(String args[]) {
        FileInputStream input1 = null;
        try {
            input1 = new FileInputStream("D:/file.txt");
        } catch(FileNotFoundException input2) {
            system.out.println("The file does not " + "exist at the location");
        }
        int m;
        try {
            while((m = input1.read()) != -1) {
                System.out.print((char)m);
            }
            input1.close();
        } catch(IOException input3) {
            system.out.println("I/O error occurred: "+ input3);
        }
    }
}

输出:代码将顺利运行并显示文件。

现在,让我们了解其他检查异常。他们之中有一些是:

SQL异常

此类异常发生在对与 SQL 语法相关的数据库执行查询时。例如,考虑以下代码片段:

public void setClientInfo ( String sname , String svalue ) throws SQLClientInfoException { try { 
        checkClosed (); ((java.sql.Connection)这个.mc)。_ _ _ setClientInfo (名称,值); } catch ( SQLException sqlEx ) { try { 
            checkAndFireConnectionError ( sqlEx );                  
        } catch ( SQLException sqlEx2 ) { SQLClientInfoException client_Ex = new SQLClientInfoException (); 
            client_Ex 。初始化原因(sqlEx2 );抛出client_Ex ;} } } 

输出:此代码将生成 SQLException。

异常

这种类型的异常发生在使用文件 I/O 流操作时。例如,考虑以下代码片段:

import java.io.*;
public class sample_IOException {
    private static String filepath = "D:\User\guest\Desktop\File2.txt";
    public static void main(String[] args) {
        BufferedReader br1 = null;
        String curline;
        try {
            br1 = new BufferedReader(new FileReader(filepath));
            while ((curline = br1.readLine()) != null) {
                System.out.println(curline);
            }
        } catch (IOException e) {
            System.err.println("IOException found :" + e.getMessage());
        } finally {
            try {
                if (br1 != null)
                    br1.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

输出:此代码将生成 IOException。

ClassNotFoundException异常

当 JVM 无法找到所需的类时,将抛出此类异常。这可能是由于命令行错误、类路径问题或缺少 .class 文件造成的。例如,考虑以下代码片段:

public class sample_ClassNotFoundException {
    private static final String CLASS_TO_LOAD = "main.java.Utils";
    public static void main(String[] args) {
        try {
            Class loadedClass = Class.forName(CLASS_TO_LOAD);
            System.out.println("Class " + loadedClass + " found!");
        } catch (ClassNotFoundException ex) {
            System.err.println("ClassNotFoundException was found: " + ex.getMessage());
            ex.printStackTrace();
        }
    }
}

输出:此代码将生成 ClassNotFoundException。

调用目标异常

这种类型的异常包装由调用的方法或构造函数抛出的异常。可以借助getTargetException方法访问抛出的异常。例如,考虑以下代码片段:

package main.samplejava;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Example {
    @SuppressWarnings("unused")
    private int test_sample(String s1) {
        if (s1.length() == 0)
            throw new IllegalArgumentException("The string should have at least one character!");
        System.out.println("Inside test_sample: argument's value equals to: "" + s1 + """);
        return 0;
    }
    public static void main(String... args) {
        try {
            Class<?> c1 = Class.forName("main.samplejava. Example");
            Object t1 = c1.newInstance();
            Method[] declared_Methods = c1.getDeclaredMethods();
            for (Method method : declared_Methods) {
                String methodName = method.getName();
                if (methodName.contains("main"))
                    continue;
                System.out.format("Invoking %s()%n", methodName);
                try {
                    method.setAccessible(true);
                    Object returnValue = method.invoke(t1, "");
                    System.out.format("%s() returned: %d%n", methodName, returnValue);
                } catch (InvocationTargetException ex) {
                    System.err.println("An InvocationTargetException was caught!");
                    Throwable cause = ex.getCause();
                    System.out.format("Invocation of %s failed because of: %s%n",
                        methodName, cause.getMessage());
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
            System.err.println("The following exception was thrown:");
            ex.printStackTrace();
        }
    }
}

输出

Invoking testMethod()
An InvocationTargetException was caught!
Invocation of testMethod failed because of: The string must contain at least one character!

输出:此代码将生成 InstantiationException。

未经检查的异常

未经检查的异常是在程序执行期间发生的那些异常。因此它们也被称为运行时异常。这些异常在编译过程中一般会被忽略。编译程序时不检查它们。例如,逻辑错误和使用不正确的 API 等编程错误。

为了说明未经检查的异常的概念,让我们考虑以下代码片段:

import java.util.Scanner;
public class Sample_RunTimeException {
    public static void main(String[] args) {
        // Reading user input
        Scanner input_dev = new Scanner(System.in);
        System.out.print("Enter your age in Numbers: ");
        int age1 = input_dev.nextInt();
        if (age1>20) {
            System.out.println("You can view the page");
        } else {
            System.out.println("You cannot view the page");
        }
    }
}

输出1

Enter your age in Numbers: 21
You can view the page

输出2

Enter your age in Numbers: Twelve
Exception in thread “main” java.util.InputMismatchException
at java.util.Scanner.throwFor (Unknown Source)
at java.util.Scanner.next (Unknown Source)
at java.util.Scanner.nextInt (Unknown Source)
at java.util.Scanner.nextInt (Unknown Source)
at exceptiondemo.sample_runtimedemo.main(Sample_RunTimeExceptionDemo.java:11)

现在,让我们了解其他未检查的异常。他们之中有一些是:

空指针异常

当您尝试借助当前值为 null 或空的引用变量访问对象时,会发生此类异常。例如,考虑以下代码片段:

// Program to demonstrate the NullPointerException
class SampleNullPointer {
    public static void main(String args[]) {
        try {
            String a1 = null; // null value
            System.out.println(a1.charAt(0));
        } catch(NullPointerException e) {
            System.out.println("NullPointerException is found in the program.");
        }
    }
}

输出:在程序中发现 NullPointerException。

数组索引越界

当您尝试访问具有无效索引值的数组时,会发生此类异常。您提供的值是负数或超出数组的长度。

例如,考虑以下代码片段:

// Program to demonstrate the ArrayIndexOutOfBoundException
class sample_ArrayIndexOutOfBound {
    public static void main(String args[]) {
        try {
            int b[] = new int[6];
            b[8] = 2; // we are trying to access 9th element in an array of size 7
        } catch(ArrayIndexOutOfBoundsException e) {
            System.out.println ("The array index is out of bound");
        }
    }
}

输出:数组索引越界

非法参数异常

每当将不适当或不正确的参数传递给方法时,就会发生这种类型的异常。例如,如果一个方法是用非空字符串作为参数定义的。但是您提供的是空输入字符串。然后,抛出 IllegalArgumentException以指示用户您不能将空输入字符串传递给该方法。

请考虑以下代码片段来演示此类异常:

import java.io.File;
public class Sample_IllegalArgumentException {
    public static String createRelativePath(String par, String f_name) {
        if (par == null)
            throw new IllegalArgumentException("You cannot provide null parent path!");
        if (f_name == null)
            throw new IllegalArgumentException("Please enter the complete filename!");        
        return par + File.separator + f_name;
    }
    public static void main(String[] args) {
        // This command will be successfully executed.
        system.out.println(IllegalArgumentExceptionExample.createRelativePath("dir1", "file1"));
        system.out.println();
        // This command will throw an IllegalArgumentException.
        System.out.println(IllegalArgumentExceptionExample.createRelativePath(null, "file1"));
    }
}
Output: This code will generate an IllegalArgumentException.

非法状态异常

当环境状态与正在执行的操作不匹配时,就会发生这种类型的异常。例如,考虑下面的代码片段,它演示了这种类型的异常:

/**
 * This code will publish the current book.
 * If the book is already published, it will throw an IllegalStateException.
 **/
public void pub() throws IllegalStateException {
    Date pub_at = getPub_at();
    if (pub_at == null) {
        setPub_at(new Date());
        Logging.log(String.format("Published '%s' by %s.", getTitle(), getAuthor()));
    } else {
        throw new IllegalStateException(
        String.format("Cannot publish '%s' by %s (already published on %s).",
            getTitle(), getAuthor(), pub_at));
    }
}

输出:此代码将生成 IllegalStateException。

如果系统中已经存在出版日期,那么它将产生一个 IllegalStateException 指示该书不能再次出版。

数字格式异常

当您将字符串传递给无法转换为数字的方法时,会发生此类异常。例如,考虑以下代码片段:

// Program to demonstrate the NumberFormatException
class Sample_NumberFormat {
    public static void main(String args[]) {
        try {
            // "Test" is not a number
            int n = Integer.parseInt ("Test") ;
            System.out.println(n);
        } catch(NumberFormatException e) {
            System.out.println("Number format exception");
        }
    }
}

输出:此代码将生成 NumberFormatException。

算术异常

当您执行不正确的算术运算时,会发生这种类型的异常。比如任意一个数除以零,就会显示这样的异常。让我们考虑以下代码片段:

// Program to demonstrate the ArithmeticException
class Sample_ArithmeticException {
    public static void main(String args[]) {
        try {
            int p = 30, q = 0;
            int r = p/q;  // It cannot be divided by zero
            System.out.println ("Result = " + r);
        } catch(ArithmeticException e) {
            System.out.println ("Number cannot be divided by 0");
        }
    }
}

输出:此代码将生成一个 ArithmeticException。

以上就是关于“Java异常类型汇总”的介绍,大家如果想了解更多相关知识,不妨来关注一下本站的Java基础教程,里面的课程内容细致全面,很适合没有基础的小伙伴学习,希望对大家能够有所帮助哦。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>