Home > Java > javaTutorial > body text

What are the ways to handle Java exceptions?

PHPz
Release: 2023-05-25 15:40:56
forward
2170 people have browsed it

What is an exception?

Exceptions are very common when we write code, because programmers spend most of their time fixing bugs. In Java, the top-level class of throwable can be divided into two, one is Error (error) and the other is Exception. (abnormal).

What are the ways to handle Java exceptions?

Error (error): The difference between Error and exception is that errors cannot be handled, but are problems caused by programmers. For example, if there is a syntax error, the programmer must check himself syntax, such as result errors (StackOverflowError and OutOfMemoryError

), then programmers need to check their own logic.

Exception (Exception): This can be handled in some ways, such as throws (declaring exceptions) that we will talk about later, try{}catch{} (handling exceptions), these are how we handle exceptions. Exceptions are divided into checked exceptions (compile-time exceptions) and unchecked exceptions (runtime exceptions).

Compile-time exception: The program cannot be compiled, which is a compile-time exception. For example: when cloning, the exception must be declared through throws.

Run-time exception: refers to the program that can be compiled, but An exception occurred while running. For example: NullPointerException,

The exception thrown is ArrayIndexOutOfBoundsException or ArithmeticException.

We can handle the above exceptions, but errors require programmers to check the code themselves.

Exception handling

We have two ways to handle it:

One is the defensive type beforehand:

boolean ret = false;
ret = Login game();
if (!ret) {
Handle login game error;
return;
} r
et = Start matching();
if (!ret) {
Handling matching errors;
return;
} r
et = game confirmation();
if (!ret) {
Handling game confirmation Error;
return;
} r
et = Select Hero();
if (!ret) {
Handle Select Hero Error;
return;
} r
et = Loading game screen();
if (!ret) {
Handle loading game error;
return;
} .
.....

The defensive type beforehand is to check whether there is an error at every step. The disadvantage of this is that the code looks very confusing and inefficient;

One is to admit the mistake afterwards:

try {
Log in to the game();
Start matching();
Game confirmation();
Select hero();
Load game screen();
...
} catch (login game exception) {
Handle login game exception;
} catch (start matching exception) {
Handle start matching exception;
} catch (game confirmation Exception) {
Handle game confirmation exception;
} catch (Exception in hero selection) {
Handle exception in hero selection;
} catch (Exception in loading game screen) {
Handle loading game Screen exception;
} .
....

This approach is to put all possible exceptions in the code in try. If an exception is found, it will be captured. Just do the operation first and deal with it if you encounter any problems.

We often use the second trycatch to make the code concise, clear and more efficient.

Exception throwing

If a piece of code does not meet expectations, we need to use the throw keyword in Java to throw an exception.

The syntax is throw new exception (the exception you want to throw)

public class TestDemo {
    public static void func(int a) {
        if(a==10) {
            throw new RuntimeException("a==10不符合预期,抛出这个异常");
        }
    }
    public static void main(String[] args) {
           func(10);
    }
}
Copy after login

Look at this code: For example, our number 10 does not meet the expectations of our program, so to throw an exception, we You can run out like this: throw new RuntimeException("a==10 does not meet expectations, throw this exception");

Handling exceptions

We usually have two ways to handle exceptions, One is to declare exceptions through throws, and the other is to check whether there are exceptions in the code block through try{}catch{}. If there is an exception, catch will catch it. If there is no exception, the following code will be normal.

throws declares exceptions

Syntax: throws exception, exception, exception...(multiple exceptions can be declared)

public class TestDemo {
    public static void function(int[] array) {
        System.out.println(array[100]);
    }
    public static void main(String[] args) {
        int[] array = {7, 8, 9, 5, 6};
        function(array);
    }
}
Copy after login

Everyone knows that there have been 100 visits here The mark is an array out-of-bounds exception:

What are the ways to handle Java exceptions?

Next, declare the exception through throws:

What are the ways to handle Java exceptions?

An error will still be reported.

When we also declare an exception to the main function:

What are the ways to handle Java exceptions?

The answer will still be an error.

So from here we draw a conclusion: Throws only tells the compiler that this exception may occur in this method. It is just a statement, but the exception is not handled. We can also find that if an exception occurs in a certain method, we will see whether this method handles the exception. If it does not handle the exception, we will see if the upper caller handles the exception. Here, func only declares the exception and does not handle the exception. Then it checks whether the upper-level caller handles the exception (that is, the main method) or does not handle the exception. Finally, it is handed over to the JVM to handle and terminate the program. Exception declarations must be of class Exception or a subclass thereof.

要处理异常,就需要使用接下来所述的try{}catch语句。

捕获异常

try{

}catch(){

}

在Java我们利用try{}catch{}来处理异常;

语法:

    try{
     //可能发生异常的代码
    }catch(异常 变量){//例如:ArrayIndexOutOfBoundsException(要捕获的异常) e(变量)
      //如果try中的代码抛出异常了,此处catch捕获时异常类型与try中抛出的异常类型一致时,
      //或者是try中抛出异常的基类时,就会被捕获到
      // 对异常就可以正常处理,处理完成后,跳出try-catch结构,继续执行后序代码
    }finally{
      //此处代码一定会执行,用于资源清理扫尾等工作
    }
Copy after login

我们先来讲一下try{}catch(){}

/*在方法中处理异常*/
public class TestDemo {
    public static void function(int[] array) throws ArrayIndexOutOfBoundsException {
        try{
            System.out.println(array[100]);
        }catch(ArrayIndexOutOfBoundsException e) {
            System.out.println("array[100]->数组下标越界异常catch->捕获成功");
        }
    }
    public static void main(String[] args) throws ArrayIndexOutOfBoundsException {
        int[] array = {7, 8, 9, 5, 6};
        function(array);
    }
}
/*在main方法中处理异常*/
public class TestDemo {
    public static void function(int[] array) throws ArrayIndexOutOfBoundsException {
            System.out.println(array[100]);
    }
    public static void main(String[] args) throws ArrayIndexOutOfBoundsException {
        int[] array = {7, 8, 9, 5, 6};
        try{
            function(array);
        }catch(ArrayIndexOutOfBoundsException e) {
            System.out.println("array[100]->数组下标越界异常catch->捕获成功");
        }
    }
}
Copy after login

我们使用try{}catch(){}就可以对异常进行处理,既可以在方法中处理异常也可以在main方法中处理异常,同时这里throws虽然没有什么用处,但是可以清晰的告诉程序员,这个方法未来可能会发生这个异常,所以还是有必要的。

try{}catch{}注意点 一:

What are the ways to handle Java exceptions?

What are the ways to handle Java exceptions?

当捕获异常成功的时候,后面的业务代码正常执行,如果没有捕获那就不会执行。

try{}catch{}注意点 二:

What are the ways to handle Java exceptions?

当try里检查到异常,catch就会捕获,计算这个异常后面还有异常也不会执行。

try{}catch{}注意点三:

throws只是声明异常,并没有处理异常,我们要通过try{}catch(){}来处理异常。

try{}catch{}注意点四:

What are the ways to handle Java exceptions?

当catch捕获的异常类型与发生异常类型不符合,就不会被捕获,就继续往外抛异常知道JVM收到后终止程序

try{}catch{}注意点五:

What are the ways to handle Java exceptions?

当发生多种异常的时候,那就要多种catch来捕获,多种异常,多次捕获。

try{}catch{}注意点六:

What are the ways to handle Java exceptions?

Exception是所有类的父类不能在前面捕获,而是应该放在最末尾进行收尾工作。

既然Exception类是所对应异常类的父类,那可不可以捕获Exception,即多次异常,一次捕获呢??

catch 进行类型匹配的时候, 不光会匹配相同类型的异常对象, 也会捕捉目标异常类型的子类对象

答案是不建议的。当代码变得复杂时,只捕获Exception类并不能明确哪些处理方式出现了问题。

打印异常信息

What are the ways to handle Java exceptions?

我们还可以利用printStackTrace来打印错误信息。

finally:

finally经常与try{}catch(){}进行一起使用,finally主要是进行资源的清理,的扫尾工作,且finally一定会被执行。

What are the ways to handle Java exceptions?

What are the ways to handle Java exceptions?

我们来看这样一段代码结果会是什么??

public class TestDemo {
    public static int function(int[] array) throws ArrayIndexOutOfBoundsException {
        try {
            System.out.println(array[100]);
        }catch(ArrayIndexOutOfBoundsException e) {
            System.out.println("array[100]->数组下标越界异常catch->捕获成功");
            return -1;
        }finally{
            System.out.println("finally主要进行资源回收和清理的扫尾工作~~~");
            return 9;
        }
    }
    public static void main(String[] args) throws ArrayIndexOutOfBoundsException,ArithmeticException {
        int[] array = {7, 8, 9, 5, 6};
        System.out.println(function(array));
        System.out.println("以下是业务代码~~~~~~");
    }
}
Copy after login

What are the ways to handle Java exceptions?

答案并不是我们想的return-1,执行结束,而是return9,我们这里可以理解为finally的9将catch里的-1覆盖。所以finally里面的代码是一定会执行的。

异常的处理流程

我的理解:

第一步检查try里面的代码里是否有异常,如果有异常catch就进行捕获,如果没有异常接着往下执行,这里catch如果没有捕获到就看一看上层调用者有没有处理,有处理就进行处理,没有处理就交给JVM终止程序。如果catch捕获到了,下面正常的业务代码正常执行。无论catch是否捕获到异常,finally代码块都将被执行。

官方:

  • 程序先执行 try 中的代码

  • 如果 try 中的代码出现异常, 就会结束 try 中的代码, 看和 catch 中的异常类型是否匹配.

  • 如果找到匹配的异常类型, 就会执行 catch 中的代码

  • 如果没有找到匹配的异常类型, 就会将异常向上传递到上层调用者.

  • 无论是否找到匹配的异常类型, finally 中的代码都会被执行到(在该方法结束之前执行).

  • 如果上层调用者也没有处理的了异常, 就继续向上传递.

  • 一直到 main 方法也没有合适的代码处理异常, 就会交给 JVM 来进行处理, 此时程序就会异常终止。

自定义异常

在我们做很大型的项目的时候,我们就会发现,我们遇到的异常,在Java中的内置异常并没有,所以我们就需要自己定义一个异常,来维护我们实际中遇到的异常。

java 中虽然已经内置了丰富的异常类, 但是并不能完全表示实际开发中所遇到的一些异常,此时需要维护符合我们实际情况的异常结构

在Java中自己声明异常,不是说你写了个异常的名字就是一个异常,而是在你自己定义的异常需要取继承原有的内置异常。

我们通过一个登陆的代码来讲解自定义异常:

class LogIn {
    private String name ="Admin";//用户名
    private String password= "CsDn1263987..0";
    public void logInFor(String name,String password) throws UserNameErrorExecption, PasswordErrorException {
        if(!this.name.equals(name)){
            throw new UserNameErrorExecption("用户名参数异常!!!");
        }
        if(!this.password.equals(password)) {
            throw  new PasswordErrorException("用户密码参数异常!!!");
        }
        System.out.println("~~~登陆成功~~~");
    }
}
public class TestDemo{
    public static void main(String[] args) throws UserNameErrorExecption, PasswordErrorException {
        LogIn logIn = new LogIn();
        //logIn.logInFor("Admin","CsDn1263987..0");
        try{
            logIn.logInFor("Admin","CsDn126398..0");
        }catch(UserNameErrorExecption nameError) {
            nameError.printStackTrace();
            System.out.println("用户名错误!!!");
        }catch(PasswordErrorException passwordError) {
            passwordError.printStackTrace();
            System.out.println("密码错误!!!");
        }
    }
}
Copy after login

自定义异常:

class PasswordError extends Exception {
     public PasswordError(String message) {
           super(message);
     }
}
Copy after login
class UserNameError extends Exception {
    public UserNameError(String message) {
        super(message);
    }
}
Copy after login

这就是我们定义的两个异常。

通过继承Exception来定义两个异常。

通常我们自定义异常类要继承Exception或者RunTimeException类,除此之外也可以定义其他类作为异常类。

  • 自定义异常通常会继承自 Exception 或者 RuntimeException

  • 继承自 Exception 的异常默认是受查异常

  • 继承自 RuntimeException 的异常默认是非受查异常

The above is the detailed content of What are the ways to handle Java exceptions?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template