当前位置:网站首页>Knowledge sorting of exception handling
Knowledge sorting of exception handling
2022-06-27 21:39:00 【continueLR】
Catalog
2. Exception inheritance structure
3. Exception structure inheritance diagram
4. There are two ways to handle exceptions :
5. Exception objects have two very important methods
1. What is an anomaly ?
Abnormal conditions during program execution are called exceptions , Exist as classes and objects , You can use the exception class , Create and instantiate exception objects . When something goes wrong JVM Meeting new Exception object .
Java Language is a perfect language , Provides exception handling mechanism , When an exception occurs during the execution of the program and the program terminates ,java It will print out the abnormal information on the console , For reference .
Meaning of existence : enhance java The robustness of the program .
2. Exception inheritance structure
Parent class :java.lang.Throwable
Subclass :Error( Error class ),Excepition( Exception class )
Excepition There are two branches :
One is a direct subclass of an exception , This is called a compile time exception , It's also called an anomaly , The programmer is required to deal with , If you don't deal with , The compiler will report an error .
The other branch is RuntimeException( Runtime exception ), It is also called non detected exception , When writing a program , Programmers can choose to do preprocessing , You can also ignore , It does not affect the compilation phase of the program .
3. Exception structure inheritance diagram

4. There are two ways to handle exceptions :
The first way to handle exceptions :
Use... At the location of the method declaration throws Keyword throw , Who calls my method , I'll throw it to whoever . Leave it to the caller to handle .
This attitude towards handling exceptions : Report .
The second way to handle exceptions :
Use try..catch Statement to catch exceptions .
This exception will not be reported , Take care of it yourself .
The exception is thrown here , No more throwing up .
Be careful :
As long as the exception is not caught , Reporting method is adopted , Subsequent code for this method does not execute .
In addition, we need to pay attention to ,try An exception occurred on a line in the statement block , The code after this line does not execute .
try..catch After catching the exception , Subsequent code can be executed .
In later development , Handle compile time exceptions , Should it be reported or captured , How to choose ?
If you want the caller to handle , choice throws Report .
In other cases, use capture .
public class ExceptionTest {
// It is generally not recommended that main Methodically used throws, Because if this exception really happens , It will be thrown to JVM.JVM Only termination .
// The function of exception handling mechanism is to enhance the robustness of the program . How can we do , The exception does not affect the execution of the program . therefore
// commonly main For exceptions in the method, it is recommended to use try..catch To capture .main Just don't keep throwing up .
/*
public static void main(String[] args) throws FileNotFoundException {
System.out.println("main begin");
m1();
System.out.println("main over");
}
*/
public static void main(String[] args) {
// 100 / 0 This is an arithmetic anomaly , This exception is a runtime exception , You're in the compilation phase , Can handle , Or not . The compiler doesn't care .
//System.out.println(100 / 0); // Don't deal with the compiler
// You can also handle .
/*
try {
System.out.println(100 / 0);
} catch(ArithmeticException e){
System.out.println(" Arithmetic is abnormal !!!!");
}
*/
System.out.println("main begin");
try {
// try Try
m1();
// The above code has an exception , Go straight into catch Execute in statement block .
System.out.println("hello world!");
} catch (FileNotFoundException e){ // catch The latter is like a formal parameter of a method .
// You can use... In this branch e quote ,e The memory address saved by reference is that new Get the memory address of the exception object .
// catch It's the branch after catching the exception .
// stay catch What do you do in the branch ? Handling exceptions .
System.out.println(" file does not exist , Possible path error , It is also possible that the file has been deleted !");
System.out.println(e); //java.io.FileNotFoundException: D:\course\01- course \ Learning methods .txt ( The system could not find the specified path .)
}
// try..catch After catching the anomaly , The code here will continue to execute .
System.out.println("main over");
}
private static void m1() throws FileNotFoundException {
System.out.println("m1 begin");
m2();
// The above code is abnormal , There is no way to execute .
System.out.println("m1 over");
}
// Nothing else , throw ClassCastException That means you're still not right FileNotFoundException To deal with
//private static void m2() throws ClassCastException{
// throw FileNotFoundException The father of IOException, This is OK . because IOException Include FileNotFoundException
//private static void m2() throws IOException {
// That's ok , because Exception Including all exceptions .
//private static void m2() throws Exception{
// throws You can also write multiple exceptions later , You can use commas to separate .
//private static void m2() throws ClassCastException, FileNotFoundException{
private static void m2() throws FileNotFoundException {
System.out.println("m2 begin");
// The compiler reported an error because :m3() Method declaration location has :throws FileNotFoundException
// We call... Here m3() No preprocessing of exceptions , So compile error .
// m3();
m3();
// If the above is abnormal , There is no way to execute !
System.out.println("m2 over");
}
private static void m3() throws FileNotFoundException {
// call SUN jdk Construction method of a class in .
// This class hasn't touched , later stage IO I know when I flow .
// We just use this class to learn the exception handling mechanism .
// Create an input stream object , The stream points to a file .
/*
What is the reason for the compilation error ?
First of all : A constructor is called here :FileInputStream(String name)
second : The constructor's declaration location has :throws FileNotFoundException
Third : See through the inheritance structure of the class :FileNotFoundException The parent class is IOException,IOException The parent class is Exception,
Finally, I learned that ,FileNotFoundException Is a compile time exception .
The reason for the error ? Compile time exceptions require the programmer to handle them at the programming stage , If you don't handle the compiler, you will report an error .
*/
//new FileInputStream("D:\\course\\01- Class opening \\ Learning methods .txt");
// We take the first approach : Use... At the location of the method declaration throws Keep throwing up .
// After an exception occurs in the code in a method body , If reported , This method ends .
new FileInputStream("D:\\course\\01- course \\ Learning methods .txt");
System.out.println(" If the above code is abnormal , Will it be implemented here ?????????????????? Can't !!!");
}
}
5. Exception objects have two very important methods
Get unusually simple description information :
String msg = exception.getMessage();
Print stack information for exception trace :
exception.printStackTrace();
public static void main(String[] args) {
// This is just for testing purposes getMessage() Methods and printStackTrace() Method .
// Here are just new An exception object was found , But the exception object is not thrown .JVM Will think this is an ordinary java object .
NullPointerException e = new NullPointerException(" Null pointer exception fdsafdsafdsafds");
// Get exception simple description information : This information is actually above the construction method String Parameters .
String msg = e.getMessage(); // Null pointer exception fdsafdsafdsafds
System.out.println(msg);
// Print exception stack information
// java When spooling exception stack trace information , It is printed by asynchronous thread .
e.printStackTrace();
for(int i = 0; i < 1000; i++){
System.out.println("i = " + i);
}
System.out.println("Hello World!");
}
}边栏推荐
- Go from introduction to actual combat - context and task cancellation (notes)
- VMware vSphere ESXi 7.0安装教程
- Acwing周赛57-数字操作-(思维+分解质因数)
- TypeScript学习
- OpenSSL 编程 一:基本概念
- VMware vSphere esxi 7.0 installation tutorial
- Goldfish rhca memoirs: do447 managing projects and carrying out operations -- creating job templates and starting jobs
- Go from introduction to actual combat -- channel closing and broadcasting (notes)
- SQL必需掌握的100个重要知识点:使用函数处理数据
- 语言弱点列表--CWE,一个值得学习的网站
猜你喜欢

Codeforces Round #723 (Div. 2)

Animal breeding production virtual simulation teaching system | Sinovel interactive

Go从入门到实战—— 多路选择和超时控制(笔记)

Go从入门到实战——任务的取消(笔记)

Go從入門到實戰——接口(筆記)

100 important knowledge points that SQL must master: sorting and retrieving data

体验Navicat Premium 16,无限重置试用14天方法(附源码)

行业案例|从零售之王看银行数字化转型的运营之道

100 important knowledge points that SQL must master: filtering data

Release of global Unicorn list in 2021: the full list of 301 Unicorn enterprises in China is coming!
随机推荐
GoLand permanently activated
创建对象时JVM内存结构
io流代码
华为伙伴暨开发者大会2022开源时刻全纪录
划重点!国产电脑上安装字体小技巧
Go from introduction to actual combat - context and task cancellation (notes)
Go从入门到实战——Panic和recover(笔记)
Go from starting to Real - Interface (note)
CORBA 架构体系指南(通用对象请求代理体系架构)
Go从入门到实战——接口(笔记)
SQL必需掌握的100个重要知识点:创建计算字段
农产品期货怎么做怎么开户,期货开户手续费多少,找谁能优惠手续费?
CEPH distributed storage
Full record of 2022 open source moment at Huawei partners and Developers Conference
oss上传调用的是哪个方法
gomock mockgen : unknown embedded interface
A set of system to reduce 10 times the traffic pressure in crowded areas
Go从入门到实战——行为的定义和实现(笔记)
本周二晚19:00战码先锋第8期直播丨如何多方位参与OpenHarmony开源贡献
Oracle的CTAS能不能将约束等属性带到新表?