您的位置:

Java抛异常总结

Java语言中异常是一个非常重要的概念,被广泛应用于程序的开发中。当程序出现错误或者异常情况时,Java将会抛出相关的异常,开发者可根据异常类型进行事件处理。异常的运用是提升程序健壮性和可读性的关键,本文从多个方面对Java抛异常进行总结。

一、Java异常的概念

Java中的异常是指在程序运行时出现的错误或者异常情况。当程序出现这些错误时,会抛出相关的异常,让程序的开发者进行事件处理。异常可以分为两类:Checked exception 和 Unchecked exception。

Checked exception是指在编译时出现的异常情况,需要对这些异常进行捕获和处理。这些异常通常是由外部因素引起,如文件操作异常、网络连接异常等。如果没有捕获这些异常,程序将无法编译通过。

Unchecked exception是指在运行时出现的异常情况,这些异常通常是由程序本身的代码错误引起的。对于这些异常,Java编译器不会进行强制处理,程序也不需要捕获这些异常。

二、Java异常的分类

在Java中,异常可以按照异常的类型进行分类。Java中提供了丰富的异常类,可以让程序开发者根据实际需要进行选择和使用。

1. ArithmeticException

public class Main {
    public static void main(String[] args) {
        int a = 10;
        int b = 0;
        System.out.println(a / b);
    }
}

上述代码执行时会抛出java.lang.ArithmeticException异常,因为0不能作为除数,这种异常常出现于算术运算中。

2. NullPointerException

public class Main {
    public static void main(String[] args) {
        String name = null;
        System.out.println(name.length());
    }
}

上述代码执行时会抛出java.lang.NullPointerException异常,因为name没有被实例化,调用length()方法将会抛出异常。

3. ArrayIndexOutOfBoundsException

public class Main {
    public static void main(String[] args) {
        int[] array = {1, 2, 3};
        System.out.println(array[5]);
    }
}

上述代码执行时会抛出java.lang.ArrayIndexOutOfBoundsException异常,因为数组下标越界,Java将会抛出异常。

三、Java异常的处理

在Java中,异常的处理通常是使用try-catch语句进行。try-catch语句可以将需要处理的代码放在try代码块中,当发生异常时,catch代码块将逐层匹配异常类型,直到匹配到对应的异常类型进行处理。

1. Try-catch语句

public class Main {
    public static void main(String[] args) {
        try {
            int a = 10;
            int b = 0;
            System.out.println(a / b);
        } catch (ArithmeticException e) {
            System.out.println("除数不能为0");
        }
    }
}

上述代码在catch代码块中捕获了ArithmeticException异常,并输出异常信息“除数不能为0”,程序将不会抛出异常而继续执行。

2. Try-catch-finally语句

public class Main {
    public static void main(String[] args) {
        try {
            System.out.println("Try block");
            throw new Exception();
        } catch (Exception e) {
            System.out.println("Catch block");
        } finally {
            System.out.println("Finally block");
        }
    }
}

上述代码在try代码块中抛出了一个异常,程序将会优先匹配异常处理代码块,然后执行finally代码块,输出结果如下:

Try block
Catch block
Finally block

四、Java自定义异常

在Java中,可以通过继承Exception类或RuntimeException类来创建自定义异常,以满足应用程序的特定需求。

1. 自定义Checked exception

public class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

public class Main {
    public static void main(String[] args) {
        try {
            throw new CustomException("Custom checked exception");
        } catch (CustomException e) {
            System.out.println(e.getMessage());
        }
    }
}

上述代码继承了Exception类并重写了父类的构造方法,创建了自定义的Checked Exception,程序在发生异常时输出自定义的异常信息。

2. 自定义Unchecked exception

public class CustomRuntimeException extends RuntimeException {
    public CustomRuntimeException(String message) {
        super(message);
    }
}

public class Main {
    public static void main(String[] args) {
        throw new CustomRuntimeException("Custom unchecked exception");
    }
}

上述代码继承了RuntimeException类并重写了父类的构造方法,创建了自定义的Unchecked Exception,程序会在运行时抛出异常并输出自定义的异常信息。

五、Java异常的日志记录

在应用程序开发中,异常的捕获和处理是必须的,但是如何诊断异常造成的问题却是另外一个问题。Java提供了日志记录的功能,可以帮助开发者更好的掌握应用程序的状态和异常信息。

1. Log4j2

Log4j2是一个非常常用的日志记录框架,可以将日志信息输出到控制台、文件、数据库等多种渠道,并支持多种日志级别。引入Log4j2可以帮助开发者更好的诊断Java应用程序中的异常信息。

public class CustomException extends Exception {
    private static final Logger LOGGER = LogManager.getLogger(CustomException.class);

    public CustomException(String message) {
        super(message);
        LOGGER.error("CustomException: " + message);
    }
}

上述代码在自定义的Checked Exception中引入了Log4j2框架,在异常捕获的时候,将异常信息输出到日志文件中,方便开发者进行诊断和定位问题。

2. 通过StackTrace获取异常信息

public class Main {
    public static void main(String[] args) {
        try {
            int a = 10;
            int b = 0;
            System.out.println(a / b);
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            System.out.println(sw.toString());
        }
    }
}

上述代码在发生异常后,通过StackTrace获取异常栈信息,并输出到控制台中,方便开发者进行诊断和定位问题。

总结

异常处理是Java编程中不可或缺的一部分,本文从Java异常的概念、分类、处理、自定义异常和日志记录等多个方面对异常进行了总结。在异常的捕获和处理过程中,开发者需要根据具体情况选择合适的异常处理方式,并利用日志记录等方式对异常进行诊断。