The underlying principle of the exception handling mechanism
Throws an exception. When executing a method, if an exception is sent, this method generates an object representing the exception and stops the current execution. path and submit the exception to jre.
Catch exception: After jre gets the exception, it feints the corresponding code to handle the exception. jre searches in the call stack of the method and traces back from the method that generated the exception until it finds the corresponding exception handling code.
Exception inheritance diagram
Ok, we now know what the definition of exception is, so how should we go about it? Catch exceptions and then handle them.
Exception handling
1. try-catch-finally structure
First we look at a piece of code:
package AbnormalTest; import java.util.InputMismatchException; import java.util.Scanner; public class test1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); try { System.out.print("请输入被除数:"); int a = input.nextInt(); System.out.print("请输入除数:"); int b = input.nextInt(); int sum = b/a; System.out.println("结果是:"+sum); System.out.println("程序无异常,执行完毕!"); }catch (Exception e){ //通用异常 //printStackTrace()方法是将堆栈异常的错误信息打印出来(后期学习框架后我们一般提交或 者回滚事务) e.printStackTrace(); System.out.println("程序异常,请重试!"); return ; }finally { //不管是否发生了异常,都会执行finally内的代码,通常用于资源的关闭 System.out.println("------------------------------"); System.out.println("程序结束,资源已经关闭,欢迎再次使用"); input.close(); //关闭Scanner对象,节省资源 } } }
Code explanation:
There are try-catch-finally structures in the above code. What are their respective functions?
try: We use try to include code that may cause exceptions
catch: As long as an exception occurs when the code in the try code block is running, catch will be entered to catch the exception
finally: No matter how the previous code is executed, the finally code block will be executed! !
Example of running results:
Normal time:
Abnormal time:
When the dividend is 0, An exception will be triggered and captured in catah, but no matter whether there is an exception or not, the program output in finally will be executed: the program is over, the resource has been closed, you are welcome to use it again
II , Multi-catch handles different exceptions:
We know that there may be more than one exception in a piece of code. For example, in the above code, there may be an exception where the dividend is divided by 0, or there may be an input exception when characters are entered for calculation, or there may be There are digital formatting exceptions, etc., so we can use multiple catches to catch exceptions:
Still take the above code as an example:
import java.util.InputMismatchException; import java.util.Scanner; public class test1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); try { System.out.print("请输入被除数:"); int a = input.nextInt(); System.out.print("请输入除数:"); int b = input.nextInt(); int sum = b/a; System.out.println("结果是:"+sum); System.out.println("程序无异常,执行完毕!"); }catch (InputMismatchException e){ //多重catch结构,这里捕捉输入异常 e.printStackTrace(); System.out.println("程序输入异常,请重试!"); }catch (Exception e){ //这里捕捉通用异常(其他异常都可以在这里进行捕捉) e.printStackTrace(); System.out.println("程序异常,请重试!"); return ; }finally { //不管是否发生了异常,都会执行finally内的代码,通常用于资源的关闭 System.out.println("------------------------------"); System.out.println("程序结束,资源已经关闭,欢迎再次使用"); input.close(); //关闭Scanner对象,节省资源 } } }
When the input is not a number:
In this way we can see that it has been caught in the first catch
3. throws declares exception/throw throws exception:
Suppose I define a method and inform that the method may send some kind of exception (declared exception). The caller must handle the exception when calling the method.
First we define an error class:
Student class:
package ExceptionText; /** * 异常测试 */ public class Student { private String name; private int age; private char sex; public void setName(String name) { this.name = name; } public String getName() { return name; } public int getAge() { return age; } public char getSex() { return sex; } public void setAge(int age) throws Exception { if (age < 101 && age > 0) { this.age = age; } else { throw new Exception("年龄输入有误!"); } } public void setSex(char sex) throws Exception { if (sex == '男' || sex == '女') { this.sex = sex; } else { throw new Exception("性别输入有误"); } } }
Test class:
package ExceptionText; public class TestMain { public static void main(String[] args) { Student stu = new Student(); stu.setName("小红"); try { stu.setAge(50); stu.setSex('k'); System.out.println("我叫:"+stu.getName()+"年龄:"+stu.getAge()+"我的性别是:"+stu.getSex()); } catch (Exception e) { e.printStackTrace(); } } }
When the entry and exit are correct:
When the age is entered incorrectly:
When the gender is entered incorrectly:
Note: If there are multiple exceptions, the first one that occurs will be thrown.
4. Custom exceptions:
When the runtime exception subclass of RuntimeException cannot meet our needs, we can also customize runtime exceptions and throw custom exceptions Information to meet our needs, but please note: Custom runtime exceptions must inherit RuntimeException! ! !
Custom exception class:
//这个类是继承了RuntimeException public class AgeException extends RuntimeException { //构造方法 public AgeException(String message) { super(message); } }
Student information class:
package CustomizeException; public class Student { private String name; private int age; private char sex; public void setName(String name) { this.name = name; } public String getName() { return name; } public int getAge() { return age; } public char getSex() { return sex; } //方法 //使用throws 来声明异常,就是这个方法内可能存在异常,先事先声明 public void setAge(int age) throws Exception { if (age < 101 && age > 0) { this.age = age; } else { //如果不符合上面的if判断 throw new Exception("年龄输入有误!"); //这里就要用thrwo 来抛出异常, } } public void setSex(char sex) throws Exception { if (sex == '男' || sex == '女') { this.sex = sex; } else { throw new AgeException("这是自定义异常,性别输入有误"); } } }
Test class:
package ExceptionText; public class TestMain { public static void main(String[] args) { Student stu = new Student(); stu.setName("小红"); try { stu.setAge(18); stu.setSex('女'); System.out.println("我叫:"+stu.getName()+"年龄:"+stu.getAge()+"我的性别是:"+stu.getSex()); } catch (Exception e) { e.printStackTrace(); } } }
The code in this part is consistent with the third part above , you can refer to the above example.
5. Common exceptions
The above is the detailed content of Example analysis of Java exception handling mechanism. For more information, please follow other related articles on the PHP Chinese website!

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.

JRE is the environment in which Java applications run, and its function is to enable Java programs to run on different operating systems without recompiling. The working principle of JRE includes JVM executing bytecode, class library provides predefined classes and methods, configuration files and resource files to set up the running environment.

JVM ensures efficient Java programs run through automatic memory management and garbage collection. 1) Memory allocation: Allocate memory in the heap for new objects. 2) Reference count: Track object references and detect garbage. 3) Garbage recycling: Use the tag-clear, tag-tidy or copy algorithm to recycle objects that are no longer referenced.

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1
Easy-to-use and free code editor