12 java exception handling, exception throwing, log, date creation

1. Concept of abnormality Exceptions refer to abnormal events that occur during program operation, which are usually cau...

1. Concept of abnormality

Exceptions refer to abnormal events that occur during program operation, which are usually caused by external problems (such as hardware errors and input errors). In object-oriented programming languages such as Java, exceptions belong to objects.
Think: why do you need exceptions? The purpose of learning exceptions is to learn to deal with exceptions and solve the problem that a small problem will not directly cause the program to stop.
The program simulates reality: get up and wash (no water?) if it doesn't solve: don't go to work. Get up, wash and go to work
Program exception: an abnormal event occurs in the code. If it is handled, the program continues. If it cannot be handled, the program terminates.

An exception is an abnormal event that occurs during the running of a program. If it is not handled, it will interrupt the running program. If processing, individual code will not execute, but the program can continue.
Java exception handling is implemented through five Keywords: try, catch, finally, throw and throws

2 try-catch

try{
There may be exceptions in the code try. If an exception occurs in the code try, the program will not terminate directly - a piece of code can only handle one exception., After the problem is solved, the code in try will not be executed. Continue to execute the code after trycatch
}Catch (catch exception){
- handle the exception after capturing the exception - whether you handle it or not, it will be solved as long as it is captured.
}Catch (catch exception){
After catching the exception, handle the exception - whether you handle it or not, as long as you catch it, it will be solved.
}Catch (catch exception){
After catching the exception, handle the exception - whether you handle it or not, as long as you catch it, it will be solved.
}finally{
Final code: code that needs to be executed whether there are exceptions or not
}

public class MainTest { public static void main(String[] args) { int result0=-1; int result1=-1; try {//try is the code where exceptions may occur int a = 1; int b = 2; result0=a/b; int c = 0; result1 = a / c;//In case of abnormal try termination, exception capture is carried out. Code other than execution is caught; program termination is not caught System.out.println("try It's over"); }catch (ArithmeticException e){//Catch exception System.out.println("An exception was caught"+e.getMessage()); } System.out.println("a/b:"+result0); System.out.println("a/c:"+result1); System.out.println("This is the last sentence of the program"); } }

56789 normally executes 10 exceptions, and the try terminates, so 11 does not execute. If it is caught, execute the code in catch. After processing, execute the code behind the try, that is, start from line 15

3 finally

public static void main(String[] args) { Scanner scanner=new Scanner(System.in); int result0=-1; int result1=-1; try { //try is the code where exceptions may occur int a = 2; int b = scanner.nextInt(); result0=a/b; int c = scanner.nextInt(); result1 = a / c;//In case of abnormal try termination, exception capture is carried out. Code other than execution is caught; program termination is not caught System.out.println("try It's over"); }catch (ArithmeticException e){//Catch exceptions: multiple catches need to pay attention to the order: from small to large System.out.println("An exception was caught"+e.getMessage()); }catch (InputMismatchException e){ System.out.println("An input exception was caught"); }catch (Exception e){//The parent class of the exception. Basically all running exceptions can be caught by him System.out.println("An exception was caught"); }finally { System.out.println("Final code--Whether there are exceptions will be executed. Can exceptions be handled"); } System.out.println("a/b:"+result0); System.out.println("a/c:"+result1); System.out.println("This is the last sentence of the program");} }

4. Throw exception:

Throw exception manually

public class Student { private String sex; public String getSex() { return sex; } // Throws declares what exception the method throws public void setSex(String sex) throws Exception { if(sex.equals("male")||sex.equals("female")){ this.sex = sex; }else{ throw new Exception("The entered gender is incorrect, please check!!"); //Throw exception } } public static void main(String[] args) { Student ss=new Student(); //To call a method that declares an exception throw, you must write the calling code to the try catch or throw it yourself try { ss.setSex("AAA"); } catch (Exception e) { e.printStackTrace();//Print information in exception stack System.out.println(e.getMessage()); } System.out.println(ss.getSex()); } }

5 types of abnormalities:


The difference between Exception and Error: the Error class is usually used to describe internal errors and resource exhausted errors in the Java operating system. It generally refers to JVM errors. The Error class Exception is relatively serious and cannot resume execution only by modifying the program itself, which is called fatal Exception. The Exception class is called non fatal Exception, which can run normally after capture and processing. It can be divided into two types : runtimeException and exceptions other than runtimeException. RuntimeException is also called Runtime Exception, that is, the Exception of the program in the running stage; Exceptions other than runtimeException are also called compile time Exception, that is, the Exception of the program in the compiling stage

6 common exception classes:

Exception classexplainIOExceptionFile read / write exceptionClassNotFoundExceptionThe required class could not be loadedNumberFormatExceptiondata in wrong formatInputMisMatchExceptionAbnormal received dataIllegalArgumentExceptionIllegal parameter receivedArrayIndexOutOfBoundsExceptionsubscript out of boundsNullPointerExceptionNull pointer exception

7 custom exception class

If the system only provides one exception class: try catch - enough. Any exception can be received with exception. These exceptions are handled for classification: different exceptions are handled differently when received. For example, the account does not have password error, and the account is locked -- it can be distinguished by different exceptions. You can customize the generalized exception to expand the exception classification:

public class WxhException extends Exception { //Override the method of the parent class public WxhException(String message) { super("wangxihao abnormal"); } } public static void main(String[] args) throws WxhException { int a = 0; int b = 34; if (a == 0){ throw new WxhException("dc"); } }

8 log

8.1 download log4j

Address: XXX

8.2 add jar to the project



9 date

package Except; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; public class data01 { public static void main(String[] args) { Date date = new Date(); long time = date.getTime();//Milliseconds from 1970 System.out.println(time); //Compare two dates, who is bigger than 1, the first is greater than the second - 1, and the small 0 is equal Date date2 = new Date(); date2.setTime(10000); System.out.println(date.compareTo(date2)); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy MM dd hh:mm:ss"); String format = simpleDateFormat.format(date); System.out.println(format); String zsStr="2000-11-11"; String lsStr="2001-11-11"; SimpleDateFormat form2=new SimpleDateFormat("yyyy-MM-dd"); try { Date zsDate=form2.parse(zsStr); Date lsDate=form2.parse(lsStr); System.out.println(zsDate.compareTo(lsDate)); }catch (ParseException e) { e.printStackTrace(); } LocalDateTime localDateTime = LocalDateTime.now(); System.out.println(localDateTime); //Date to string DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy year MM month"); String format1 = localDateTime.format(timeFormatter); System.out.println(format1); //Parse the string into the parse method of date: LocalDateTime DateTimeFormatter formatter2=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String str="2000-11-11 12:12:12"; LocalDateTime tt= LocalDateTime.parse(str,formatter2); System.out.println(tt); } }

After 1.8

LocalDateTime now = LocalDateTime.now();//New time System.out.println(now); DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy year MM month dd hh:mm:ss"); String format = dateTimeFormatter.format(now); System.out.println(format); LocalDate of = LocalDate.of(2020, 12, 14); DateTimeFormatter dateTimeFormatter01 = DateTimeFormatter.ofPattern("yyyy year MM month dd"); String format1 = dateTimeFormatter01.format(of); System.out.println(format1); String da = "2020-11-01 00:00:00"; DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");//Chinese characters cannot be added at the first initialization of user-defined time LocalDateTime parse = LocalDateTime.parse(da, dateTimeFormatter2); System.out.println(parse); // DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // String str = "2020-11-11 12:12:12"; // LocalDateTime tt = LocalDateTime.parse(da, formatter2); // System.out.println(tt); LocalDateTime localDateTime = parse.plusDays(5).plusHours(10).minusMinutes(20);//Minus 20 minutes System.out.println(localDateTime); DateTimeFormatter dd = dateTimeFormatter.ofPattern("yyyy year MM month dd"); String format2 = dd.format(localDateTime); System.out.println(format2);

21 November 2021, 20:36 | Views: 9309

Add new comment

For adding a comment, please log in
or create account

0 comments