当前位置:网站首页>day10_ Exception handling & enumeration
day10_ Exception handling & enumeration
2022-07-29 06:32:00 【Fat uncle talking about Java】
exception handling & enumeration
Learning goals :
1. Have a good command of java Exception handling mechanism of
2. Master enumeration data types
One 、 exception handling
1.1 What is an anomaly ?
In the process of project development using computer language , Even if the programmer writes the code perfectly , Some problems will still be encountered during the operation of the system , Because many problems can't be avoided by code , such as : Format of customer input data , Whether the read file exists , Whether the network is always maintained Unobstructed, etc .
abnormal : stay Java In language , The abnormal situation in program execution is called “ abnormal ”.( Syntax errors in the development process are not exceptions )
1.2 java Abnormal system of
java The abnormal system of is as follows :
Throwable Is the root class of the exception system , Provides a large number of exception handling methods , Subclasses have Exception and Error, Their respective meanings are as follows :
Error:Java Serious problems that virtual machines can't solve . Such as :JVM System internal error 、 Serious situations such as resource exhaustion . such as :
StackOverflowError
Generally, exception handling code is not written , Programmers should try to avoid this situation from the logic of the program .Exception: General problems caused by programming errors or accidental external factors , You can use targeted code for processing ;Exception Exceptions are divided into compile time exceptions and run-time exceptions
Compile time exception : Both exceptions that occur during the compilation phase , It refers to the exceptions that programmers must deal with , Otherwise, it will have unpredictable consequences for the program ; For such exceptions, programmers must handle or throw exceptions .
Runtime exception : It means that no exceptions are reported in the compilation stage , Exceptions reported during operation ; Such exceptions generally refer to logic errors in programming , Such as array out of bounds exception , Null pointer exception, etc , At this time, programmers are required to avoid these problems from the programming logic . Of course, there are also some runtime exceptions that are not caused by program programming , If arithmetic is abnormal, the denominator is 0, The denominator is entered by the customer , Then this exception is not a runtime exception caused by programmer programming , Exception handling required .
1.3 Common exceptions
Common runtime exceptions are :
- java.lang.RuntimeException
- ClassCastException
- ArrayIndexOutOfBoundsException
- NullPointerException
- ArithmeticException
Common compile time exceptions are :
- java.io.IOExeption
- FileNotFoundException
1.4 exception handling throws
In the process of defining methods , There may be some exceptions in the statement of the method body , But it's not sure how to handle this exception , The declaration that the method should display throws an exception , It indicates that these exceptions may occur in this method , But no treatment was made , Leave it to the caller of the method .
Use... In the method declaration throws Statement can declare a list of exceptions thrown ,throws The latter exception type can be the exception type generated in the method , It can also be its parent class .
Example 1: Define math classes and point out possible exceptions
//1. Defining interfaces
public interface MyMath{
//1. Define the division specification Tell the implementer that exceptions may occur
public int div(int i,int j) throws Exception;
}
//2. Define math classes
class MyMathImpl implements MyMath{
@Override // 3. Define math classes It is for others to tell the caller that there is a risk .
public int div(int i, int j) throws Exception {
return i/j;
}
}
Be careful : The exception thrown by the subclass cannot be greater than the exception of the parent class
1.5 exception handling try … catch … finally
When calling methods with exceptions , We can make corresponding exception handling according to whether there are abnormal conditions , The grammar is as follows :
Example : Call the method in the above mathematical class , And handle exceptions
public interface MyMath{
//1. Define the division specification Tell the implementer that exceptions may occur
public int div(int i,int j) throws Exception;
/* Program entrance */
public static void main(String[] args) {
// Create objects
MyMath myMath = new MyMathImpl();
try {
// Code with possible exception
myMath.div(1,0);
} catch (Exception e) {
// Code that runs abnormally
e.printStackTrace();
} finally {
// Code that must execute
System.out.println(" The most important code to execute ");
}
}
}
//2. Define math classes
class MyMathImpl implements MyMath{
@Override // 3. Define math classes It is for others to tell the caller that there is a risk .
public int div(int i, int j) throws Exception {
return i/j;
}
}
1.6 Throw an exception manually throw
Java Exception class objects are automatically generated and thrown by the system except when exceptions occur during program execution , It can also be manually created and thrown as needed ; The exception thrown manually must be Throwable
Or an instance of its subclass .
Example 1: Throw an exception manually
/** * Throw an exception manually */
public class ThrowDemo {
// Define a salary verification method , Salary cannot be negative
public static int sal(int sal) throws Exception{
// If the salary is negative, it will be abnormal
if(sal<0) {
//3. Create a Throwable Subclass exception
Exception exception = new Exception(" Salary cannot be negative ");
//RuntimeException exception = new RuntimeException(" Salary cannot be negative ");
//4. Throw an exception manually
throw exception;
}
return sal;
}
public static void main(String[] args) {
try {
sal(-5);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
1.7 Custom exception
The process of customizing exception classes is as follows :
- In a general way , User defined exception classes are
RuntimeException
Subclasses of . - Custom exception classes usually need to write several overloaded constructors .
- Custom exceptions need to provide serialVersionUID
How to use custom exceptions :
- Custom exception through throw Throw out .
- The most important thing about custom exceptions is the name of the exception class , When an exception occurs , You can determine the type of exception by name
Example 1: Custom negative exception
public class FuShuException extends RuntimeException {
private static final long serialVersionUID = 1L;
public FuShuException() {
}
public FuShuException(String message) {
super(message);
}
}
public class FuShuExceptionTest {
public static double getSalary(double money) {
if(money<0) {
throw new FuShuException(" Salary cannot be negative ");
}
return money;
}
public static void main(String[] args) {
getSalary(-10);
}
}
1.8 Summary
java Abnormal system
Exception handling mechanism throws And try … catch … finally
The difference between compile time and run time exceptions
Throw an exception manually throw
Custom exception
Two 、 enumeration
2.1 Enumerate introductory cases
JDK5 Enumeration technology appeared in , And separate keywords Enum
What is enumeration ? Enumeration is to enumerate fixed values one by one ; for example : Season can only use spring 、 In the summer 、 autumn 、 In the winter ; Another example is month 1-12 month ; In, say, a week 1-7.
Why do I need to enumerate data types ? We find that there are often such requirements in development : It is necessary to list several fixed values one by one , These fixed values cannot be exceeded .
Example 1: Student grade
/** * demand : The grade of students can only be A、B、C */
public class Student {
private String name;
private String grade;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
if(grade.equals("A") || grade.equals("B") || grade.equals("C")){
this.grade = grade;
}else {
throw new RuntimeException(" Not a legal grade ");
}
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", grade='" + grade + '\'' +
'}';
}
public static void main(String[] args) {
Student xiaoMing = new Student();
xiaoMing.setGrade("D");
xiaoMing.setName(" Xiao Ming ");
System.out.println(xiaoMing);
}
}
Problems like the above can be solved by enumerating
** enumeration : Class has only a limited number of objects , affirmatory . Examples are as follows : **
- week :Monday( Monday )、…、Sunday( Sunday )
- season :Spring( Spring Festival )…Winter( winter )
- Thread state : establish 、 be ready 、 function 、 Blocking 、 Death
Implementation of enumeration class :JDK5
You need to customize the enumeration class before ;JDK5
Newly added enum
Keyword is used to define enumeration classes
2.2 Manually implement enumeration
How to manually implement enumeration classes ?
- The constructor of the privatized class , Ensure that its objects cannot be created outside of the class
- Create an instance of the enumeration class inside the class . Declare as :public static final
Example 1: Custom level enumeration , And Application
public class Student {
private String name;
private Grade grade;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Grade getGrade() {
return grade;
}
public void setGrade(Grade grade) {
this.grade = grade;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", grade=" + grade +
'}';
}
public static void main(String[] args) {
Student xiaoMing = new Student();
xiaoMing.setName(" Xiao Ming ");
xiaoMing.setGrade(Grade.A);
System.out.println(xiaoMing);
}
}
// Custom enumeration class
class Grade{
//1. Private constructor
private Grade(){
}
//2. Public static constant light enumeration instances
public static final Grade A = new Grade();
public static final Grade B = new Grade();
public static final Grade C = new Grade();
}
2.3 Use enum Define enumeration
Use enum The enumeration class defined inherits by default java.lang.Enum class , So you can't inherit other classes
- Constructors of enumeration classes can only use private Permission modifier
- All instances of an enumeration class must be explicitly listed in the enumeration class (, Separate ; ending ). The listed instance system will automatically add public static final modification
- The enumeration class object must be declared on the first line of the enumeration class
Example 1: Use enum Define enumeration
public enum Grade {
/*A(),B(),C(); Write all mode */
A,B,C; // Shorthand mode
}
// Test use
public class Student {
private String name;
private Grade grade;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Grade getGrade() {
return grade;
}
public void setGrade(Grade grade) {
this.grade = grade;
}
@Override
public String toString() {
return "Student [name=" + name + ", grade=" + grade + "]";
}
public static void main(String[] args) {
Student anqila = new Student();
anqila.setGrade(Grade.A);
anqila.setName(" Angela ");
System.out.println(anqila);
}
}
Example 2: Define enumerations with constructor parameters
public enum Grade {
//3. Define enumeration fixed values
A("85-100"),B("75-84"),C("60-74");
//1. Defining attributes
private String score;
//2. Assign values through construction methods
private Grade(String score){
this.score = score;
}
//4. You can add getter and setter Method
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
}
public class Student {
private String name;
private Grade grade;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Grade getGrade() {
return grade;
}
public void setGrade(Grade grade) {
this.grade = grade;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", grade=" + grade +
'}';
}
public static void main(String[] args) {
Student xiaoMing = new Student();
xiaoMing.setName(" Xiao Ming ");
xiaoMing.setGrade(Grade.A);
System.out.println(xiaoMing);
System.out.println(Grade.A.getScore());
}
}
And the general Java Similar to class , Enumeration classes can implement one or more interfaces . If each enumeration value behaves the same way when calling the implemented interface method , Then, as long as the method is implemented uniformly . If you need each enumeration value to behave differently in the interface method of the call implementation , Let each enumeration value implement the method separately .
Example 3: Implement the enumeration definition and use of interfaces
//1. Defining interfaces
interface GradeInter{
public abstract String getStr();
}
//2. Enumerations are special classes that implement interfaces
public enum Grade implements GradeInter{
//A("85-100"),B("75-84"),C("60-74");
A("85-100"){
@Override
public String getStr() {
return " good ";
}
},
B("75-84"){
@Override
public String getStr() {
return " good ";
}
},
C("60-74"){
@Override
public String getStr() {
return " pass ";
}
};
// Defining attributes
private String score;
// Define a private constructor
private Grade5(String score){this.score=score;}
// Unified implementation of abstract methods
/* @Override
public String getStr() {
return " Pass the exam ";
}*/
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
}
public class Student {
private String name;
private Grade grade;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Grade getGrade() {
return grade;
}
public void setGrade(Grade grade) {
this.grade = grade;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", grade=" + grade +
'}';
}
public static void main(String[] args) {
Student xiaoMing = new Student();
xiaoMing.setName(" Xiao Ming ");
xiaoMing.setGrade(Grade.A);
//1. see A Grade scores
System.out.println(Grade.A.getScore());
//2. see A Description of grade
System.out.println(Grade.A.getStr());
}
}
2.4 Enumeration in switch Application in structure
JDK5
Can be found in switch Use in expressions enum
Defines the object of the enumeration class as an expression , case Clause can directly use the name of the enumeration value , You don't need to add an enumeration class as a qualification .
Example 1: stay switch Season enumeration is used in
public enum Season {
//1. In the spring 、 In the summer 、 In the fall 、 In the winter 、
SPRINGTIME,SUMMER,AUTUMN,WINTER;
}
public class SeasonDemo {
public static void main(String[] args) {
switch(Season.SPRINGTIME){
case SPRINGTIME:
System.out.println(" spring ");
break;
case SUMMER :
System.out.println(" summer ");
break;
case AUTUMN :
System.out.println(" autumn ");
break;
case WINTER :
System.out.println(" winter ");
break;
}
}
}
2.5 Common methods of enumeration
The common methods of enumeration are as follows :
Example 1: Common methods of enumeration
public class EnumMethod {
//1. Enumerate common methods
public static void main(String[] args) {
//1. Get the enumeration name
String name = Grade.A.name();
System.out.println(name);
//2. Convert the enumeration name of the string to the enumeration value
Grade a = Grade.valueOf("A");
System.out.println(a);
//3. Returns the subscript value in the array where the enumeration value is located
int index = Grade.B.ordinal();
System.out.println(index);
//4. Return the array container of enumeration instances
Grade[] values = Grade.values();
for(int i=0;i<values.length;i++){
System.out.println(values[i]);
}
}
}
2.6 Summary
- Enumeration is a special class , Enumeration class .
- Use enum The defined enumeration inherits by default java.lang.Enum. So you can use the parent class directly Enum Methods .
- Enumerate every enumeration value declared All static constants .
- Enumeration can implement interfaces , Abstract methods can be implemented uniformly , You can also implement abstract methods alone
jdk5
in the future switch Support enumeration .
3、 ... and 、 summary
- Abnormal system
- exception handling throws
- exception handling try … catch … finally
- Throw an exception manually throw
- Custom exception
- The basic use of enumeration
- Enumerate implementation interfaces
- Enumerate common methods
边栏推荐
猜你喜欢
使用STP生成树协议解决网络中的二层环路问题
Unity初学4——帧动画以及主角攻击(2d)
虹科分享 | 测试与验证复杂的FPGA设计(2)——如何在IP核中执行面向全局的仿真
虹科Automation softPLC | MoDK运行环境与搭建步骤(1)——运行环境简介
Personal views on time complexity
虹科分享 | 带您全面认识“CAN总线错误”(一)——CAN总线错误与错误帧
六、 网络互联与互联网
虹科 | 使用JESD204串行接口高速桥接模拟和数字世界
Official tutorial redshift 04 rendering parameters
Unity中简单的cubecap+fresnel shader的实现
随机推荐
What is the lifecycle of automated testing?
Vivado IP核之定点数转为浮点数Floating-point
Arrays&Object&System&Math&Random&包装类
V-ray 5 ACEScg 工作流程设置
Vivado IP核之浮点数加减法 Floating-point
Unity初学2——瓦片的制作以及世界的交互(2d)
官方教程 Redshift 02 4中GI引擎概述及总结
Leetcode 19. delete the penultimate node of the linked list
FPGA—奇偶数分频和小数分频代码例程
day14_单元测试&日期常用类&字符串常用类
EtherCAT主站掉线后,如何保证目标系统免受故障影响?
基于FPGA的IIR型滤波器设计
Leetcode 344. reverse string
官方教程 Redshift 07 Instances and Proxy
7110 digital trend 2 solution
Self study understanding of [chain forward star]
浅谈缺陷描写样式
unsigned right shift
Noi online 2022 popular group problem solving & personal understanding
虹科Automation softPLC | 虹科KPA MoDK运行环境与搭建步骤(2)——MoDK运行环境搭建