Home >Java >javaTutorial >Example analysis of Java 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.
Ok, we now know what the definition of exception is, so how should we go about it? Catch exceptions and then handle them.
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
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
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.
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.
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!