当前位置:网站首页>Common API classes and exception systems
Common API classes and exception systems
2022-07-06 00:22:00 【Wang Xiaoya】
1. Commonly used API
1.1 Math( application )
Application program interface ( English :Application Programming Interface, abbreviation :API), Also known as application programming interface , It is the agreement of linking different components of the software system .
API The main purpose is to provide the ability for applications and developers to access a set of routines , Without access to the source code , Or understand the details of the internal working mechanism . Provide API The software of the defined function is called this API The implementation of the .API It's an interface , Therefore, it is an abstraction .
1、Math Class Overview
- Math Contains methods for performing basic number operations
2、Math How to call methods in
- Math No construction method in class , But the internal methods are static , You can use the Class name . To call
3、Math Common methods of class
Method name Method name explain public static int abs(int a) Returns the absolute value of the parameter public static double ceil(double a) Returns the smallest... That is greater than or equal to the parameter double value , It's a whole number public static double floor(double a) Returns the maximum... That is less than or equal to the parameter double value , It's a whole number public static int round(float a) Return the nearest parameter to the round int public static int max(int a,int b) Return to two int The larger of the values public static int min(int a,int b) Return to two int The smaller of the values public static double pow (double a,double b) return a Of b The value of the power public static double random() The return value is double Positive value of ,[0.0,1.0)
example :
package com.com.object_11.MathTest_01;
//Math Class common methods
public class MathDemo {
public static void main(String[] args) {
//public static int abs(int a) Returns the absolute value of the parameter
System.out.println(Math.abs(66)); //66
System.out.println(Math.abs(-66)); //66
System.out.println("---------------");
// public static double ceil(double a) Returns the smallest... That is greater than or equal to the parameter double value , It's a whole number
System.out.println(Math.ceil(6.18)); //7.0
System.out.println(Math.ceil(6.65)); //7.0
System.out.println("---------------");
// public static double floor(double a) Returns the maximum... That is less than or equal to the parameter double value , It's a whole number
System.out.println(Math.floor(6.18)); //6.0
System.out.println(Math.floor(6.65)); //6.0
System.out.println("---------------");
// public static int round(float a) Return the nearest parameter to the round int
System.out.println(Math.round(6.18)); //6
System.out.println(Math.round(6.65)); //7
System.out.println("---------------");
// public static int max(int a,int b) Return to two int The larger of the values
System.out.println(Math.max(6,9)); //9
System.out.println("---------------");
// public static int min(int a,int b) Return to two int The smaller of the values
System.out.println(Math.min(6,9)); //6
System.out.println("---------------");
// public static double pow (double a,double b) return a Of b The value of the power
System.out.println(Math.pow(2,7)); // 128 2^7
System.out.println("---------------");
// public static double random() The return value is double Positive value of ,[0.0,1.0)
System.out.println(Math.random()); //0.14007993398889917 [0.0,1.0) Can't get at random 1
System.out.println(Math.random()*100); //55.15963738381813 [0.0,100.0) Can't get at random 100
System.out.println((int)(Math.random()*100)); //7 Forced conversion to int type 0-99 Random
System.out.println((int)(Math.random()*100)+1); //27 Forced conversion to int type After one 0-100 Random
}
}
1.2 System( application )
System Represents the system of the program , Some corresponding system attribute information is provided , And system operation .System class You cannot create objects manually , Because the construction method is private modification , Prevent the outside world from creating objects .System All of the classes are static Method , Just access the class name .
- System Common methods of class
Method name | explain |
---|---|
public static void exit(int status) | Terminate the currently running Java virtual machine , Non zero means abnormal termination |
public static long currentTimeMillis() | Return current time ( In Milliseconds ) Get the current system time and 1970 year 01 month 01 Japan 00:00 The millisecond difference between the points |
- Sample code
package com.com.object_11.APITest_01;
public class SystemDemo {
public static void main(String[] args) {
// System.out.println(" Start ");
public static void exit(int status): Terminate the currently running Java virtual machine , Non zero means abnormal termination
// System.exit(0); // It should have output “ Start end ”,exit Terminate it , So it only outputs “ Start ”
// System.out.println(" end ");
// public static long currentTimeMillis(): Return current time ( In Milliseconds )
// Get the current system time and 1970 year 01 month 01 Japan 00:00 The millisecond difference between the points
System.out.println(System.currentTimeMillis()); // 2022/6028 17:48 1656409731638
System.out.println(System.currentTimeMillis() * 1.0 / 1000 / 60 / 60 / 24 / 365 + " year ");
// It's converted into 52.524408030124306 year 1000ms = 1 s
}
}
- demand : Output at console 1-10000, Calculate how many milliseconds this code executed
public class SystemDemo {
public static void main(String[] args) {
// Get the start time node
long start = System.currentTimeMillis();
for (int i = 1; i <= 10000; i++) {
System.out.println(i);
}
// Get the time node after the code runs
long end = System.currentTimeMillis();
System.out.println(" Total time consuming :" + (end - start) + " millisecond ");
}
}
1.3 Object Class toString Method ( application )
Object Class Overview
- Object Is the root of the class hierarchy , Each class can put Object As a superclass . All classes inherit directly or indirectly from this class , let me put it another way , The methods of this class , All classes will have one
How to view the method source code
- Selection method , Press down Ctrl + B
rewrite toString Method of method
- Alt + Insert choice toString
- In the blank area of the class , Right click -> Generate -> choice toString
toString The role of methods :
- In a good format , More convenient display of attribute values in objects
Sample code :
package com.com.object_11.APITest_01;
// Definition Student class
public class ObjectStudent extends Object {
// Because the test class uses Object Class toString Method , So it's equivalent to inheriting Object
// Yes 4 Attributes :
private String name;
private int age;
private String school;
private String major;
// Space parameter structure
public ObjectStudent(){
}
// There are parametric structures
public ObjectStudent(String name,int age){
this.name = name;
this.age = age;
}
public ObjectStudent(String name,int age,String school){
this.name = name;
this.age = age;
this.school = school;
}
public ObjectStudent(String name,int age,String school,String major){
this.name = name;
this.age = age;
this.school = school;
this.major = major;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
// Print
public void show(){
System.out.println(" Student "+name+" Age "+age+" year , Study in "+school+major+" major ");
}
@Override //toString Method rewriting Alt+Insert,toString Method
public String toString() {
return "ObjectStudent{" +
"name='" + name + '\'' +
", age=" + age +
", school='" + school + '\'' +
", major='" + major + '\'' +
'}';
}
}
package com.com.object_11.APITest_01;
public class ObjectDemo {
public static void main(String[] args) {
ObjectStudent s = new ObjectStudent();
s.setName(" Lixiaolang ");
s.setAge(10);
s.setSchool(" Youzhi middle school ");
s.setMajor(" Magic major ");
System.out.println(s); //[email protected]
System.out.println(s.toString()); //[email protected]
// ObjectStudent{name=' Lixiaolang ', age=10, school=' Youzhi middle school ', major=' Magic major '}
// ObjectStudent{name=' Lixiaolang ', age=10, school=' Youzhi middle school ', major=' Magic major '}
/* public void println(Object x) { String s = String.valueOf(x); synchronized(this) { this.print(s); this.newLine(); } } */
/* public static String valueOf(Object obj) { return obj == null ? "null" : obj.toString(); }*/
/* public String toString() { return this.getClass().getName() + "@" + Integer.toHexString(this.hashCode()); }*/
}
}
- Running results :
ObjectStudent{
name=' Lixiaolang ', age=10, school=' Youzhi middle school ', major=' Magic major '}
ObjectStudent{
name=' Lixiaolang ', age=10, school=' Youzhi middle school ', major=' Magic major '}
1.4 Object Class equals Method ( application )
equals The role of methods
- For comparison between objects , return true and false Result
- give an example :s1.equals(s2); s1 and s2 Two objects
rewrite equals Method scenario
- You don't want to compare the address values of objects , When you want to compare with object properties .
rewrite equals Method of method
- alt + insert choice equals() and hashCode(),IntelliJ Default, All the way next,finish that will do
- In the blank area of the class , Right click -> Generate -> choice equals() and hashCode(), The following is the same as above .
Sample code :
class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public boolean equals(Object o) {
//this -- s1
//o -- s2
Compare the addresses , If the same , Go straight back to true
if (this == o) return true;
```java
// Judge whether the parameter is null
// Determine whether two objects come from the same class
if (o == null || getClass() != o.getClass()) return false;
// Move down
Student student = (Student) o; //student -- s2
// Compare ages
if (age != student.age) return false;
// Compare names for equality
return name != null ? name.equals(student.name) : student.name == null;
}
}
public class ObjectDemo {
public static void main(String[] args) {
Student s1 = new Student();
s1.setName(" Brigitte Lin ");
s1.setAge(30);
Student s2 = new Student();
s2.setName(" Brigitte Lin ");
s2.setAge(30);
// demand : Compare the contents of two objects
System.out.println(s1.equals(s2));
}
}
1.5 Bubble sorting principle ( understand )
- Bubble sort Overview
- A way of sorting , Compare the adjacent data in the data to be sorted , Put larger data behind , Operate all data in turn , Until all data are sorted as required
- If there is n Data to sort , In total, we need to compare n-1 Time
- After each comparison , The next comparison will involve less data
1.6 Bubble sort code implementation ( understand )
- Code implementation
/* Bubble sort : A way of sorting , Compare the adjacent data in the data to be sorted , Put larger data behind , Operate all data in turn , Until all data are sorted as required */
public class ArrayDemo {
public static void main(String[] args) {
// Define an array
int[] arr = {
24, 69, 80, 57, 13};
System.out.println(" Before ordering :" + arrayToString(arr));
// Here minus 1, Is to control the number of comparisons per round
for (int x = 0; x < arr.length - 1; x++) {
// -1 To avoid index overruns ,-x It is to improve the comparative efficiency
for (int i = 0; i < arr.length - 1 - x; i++) {
if (arr[i] > arr[i + 1]) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
}
System.out.println(" After ordering :" + arrayToString(arr));
}
// The elements in the array form a string according to the specified rules :[ Elements 1, Elements 2, ...]
public static String arrayToString(int[] arr) {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < arr.length; i++) {
if (i == arr.length - 1) {
sb.append(arr[i]);
} else {
sb.append(arr[i]).append(", ");
}
}
sb.append("]");
String s = sb.toString();
return s;
}
}
1.7 Arrays( application )
Arrays The common method of
Method name explain public static String toString(int[] a) Returns a string representation of the contents of the specified array public static void sort(int[] a) Arranges the specified array in numerical order Tool design ideas
1、 Construction method private modification
In order to prevent the outside world from creating objects2、 For members public static modification
In order to use the class name to access the member method
package com.com.object_11.APITest_01.Arrays;
import java.util.Arrays;
//public static String toString(int[] a) Returns a string representation of the contents of the specified array |
//public static void sort(int[] a) Arranges the specified array in numerical order |
public class ArraysDemo {
public static void main( String[] args) {
// Define an array
int[] arr = {
24,69,80,57,13};
System.out.println(" Before ordering :" + Arrays.toString(arr));
// Before ordering :[24, 69, 80, 57, 13]
Arrays.sort(arr) ;
System.out.println(" After ordering :" + Arrays.toString(arr));
// After ordering :[13, 24, 57, 69, 80]
}
}
2. Date class
2.1 Date class ( application )
Date Class Overview
Date Represents a specific time , Accurate to milliseconds
Date Class constructor
Method name explain public Date() Allocate one Date object , And initialization , So that it represents the time it is allocated , Accurate to milliseconds public Date(long date) Allocate one Date object , And initialize it to represent the specified number of milliseconds from the standard reference time Sample code
package com.com.object_11.APITest_01.Date;
import java.util.Date;
public class DateDemo001 {
public static void main(String[] args) {
// public Date() Allocate one Date object , And initialization , So that it represents the time it is allocated , Accurate to milliseconds
Date d1 = new Date(); // It's using java.util Created Date
System.out.println(d1);
//public Date(long date) Allocate one Date object ,
// And initialize it to represent the specified number of milliseconds from the standard reference time
// If the given millisecond value contains time information , Then the driver will set the time component to correspond to zero GMT Default time zone for ( Running the application Java The time zone of the virtual machine ).
//date - 1970 year 1 month 1 Milliseconds in days ,00:00:00 GMT No more than 8099 The millisecond of a year indicates . Negative said 1970 year 1 month 1 Japan 00:00:00 GMT The number of milliseconds before .
long date = 1000*60*60; // Hours , So it's the whole hour ,1970 year 1 month 1 Japan 1:00, With time zone
Date d2 = new Date(date);
System.out.println(d2);
}
}
//Wed Jun 29 09:35:17 CST 2022
//Thu Jan 01 09:00:00 CST 1970
2.2Date Class common methods ( application )
Common methods
Method name explain public long getTime() Get the date object from 1970 year 1 month 1 Japan 00:00:00 The millisecond value up to now public void setTime(long time) Setup time , Given is the millisecond value
public void setTime(long time) If the given millisecond value contains time information , Then the driver will set the time component to correspond to zero GMT Default time zone for ( Running the application Java The time zone of the virtual machine ).
date - 1970 year 1 month 1 Milliseconds in days ,00:00:00 GMT No more than 8099 The millisecond of a year indicates . Negative said 1970 year 1 month 1 Japan 00:00:00 GMT The number of milliseconds before .
- Sample code
package com.com.object_11.APITest_01.Date;
import java.util.Date;
public class DateDemo002 {
public static void main(String[] args) {
// Create date object
Date d = new Date();
//public long getTime(): Get the date object from 1970 year 1 month 1 Japan 00:00:00 The millisecond value up to now
System.out.println(d.getTime());
System.out.println(d.getTime() * 1.0 / 1000 / 60 / 60 / 24 / 365 + " year ");
//1656469559780
//52.5263051680619 year
// public void setTime(long time); Setup time , Given is the millisecond value
// long time = 1000 * 60 * 60;
long time = System.currentTimeMillis();
d.setTime(time);
System.out.println(d);
// Wed Jun 29 10:21:40 CST 2022
}
}
2.3SimpleDateFormat class ( application )
SimpleDateFormat Class Overview
SimpleDateFormat It's a concrete class , Used to format and parse dates in locale sensitive ways .
We focus on date formatting and parsing
SimpleDateFormat Class constructor
Method name explain public SimpleDateFormat() Construct a SimpleDateFormat, Use default mode and date format public SimpleDateFormat(String pattern) Construct a SimpleDateFormat Use the given pattern and default date format SimpleDateFormat Common methods of class
- format ( from Date To String)
- public final String format(Date date): Format the date as a date / Time string
- analysis ( from String To Date)
- public Date parse(String source): Parse the text from the beginning of the given string to generate the date
- format ( from Date To String)
Code
package com.com.object_11.APITest_01.Date;
// Toxic poison
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/*SimpleDateFormat Class constructor public SimpleDateFormat() Construct a SimpleDateFormat, Use default mode and date format public SimpleDateFormat(String pattern) Construct a SimpleDateFormat Use the given pattern and default date format - SimpleDateFormat Common methods of class - format ( from Date To String) - public final String format(Date date): Format the date as a date / Time string - analysis ( from String To Date) - public Date parse(String source): Parse the text from the beginning of the given string to generate the date */
public class SimpleDateFormatDemo {
public static void main(String[] args) throws ParseException {
// format ( from Date To String)
// Parameterless construction creates objects
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(); // No arguments structure
// How to create sdf.format(d); then Ctrl+Alt+v Automatic generation
String s = sdf.format(d);
// Output this string
System.out.println(s);
//2022/6/29 In the morning 11:03 ( Default mode )
System.out.println("-----------");
// format ( from Date To String)
// Parameterless construction creates objects
Date d1 = new Date();
// SimpleDateFormat sdf = new SimpleDateFormat();
// Remove the nonparametric structure , Write it yourself
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy year MM month dd Japan HH:mm:ss"); // Mm / DD / yyyy HHM / S
// How to create sdf.format(d1); then Ctrl+Alt+v Automatic generation
String s1 = sdf.format(d1);
// Output this string
System.out.println(s1);
// ( Default mode )
System.out.println("-----------");
// ( from String To Date)
String ss = "2025-06-29 11:20:00";
//ParseException Report errors , Parsing exceptions
// SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy year MM month dd Japan HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dd = sdf2.parse(ss);
System.out.println(dd);
}
}
2.4 Date tool case ( application )
Case needs
Define a date tool class (DateUtils), There are two methods : Converts the date to a string in the specified format ; Parse the string into a date in the specified format , Then define a test class (DateDemo), Test the method of the date tool class
Code implementation
- Tool class
package com.com.object_11.APITest_01.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtils {
// Constructor private ( The outside world cannot create objects )
private DateUtils() {
}
// Member method static ( In the future, call... By class name )
// Converts the date to a string in the specified format
// return type :String
// Parameters :Date date,String format
public static String dataToString(Date date, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
String s = sdf.format(date);
return s;
}
/* Parse the string into a date in the specified format return type :Date Parameters :string s, String format*/
public static Date stringToDate(String s, String format) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date d = sdf.parse(s);
return d;
}
}
- Test class
package com.com.object_11.APITest_01.Date;
import java.text.ParseException;
import java.util.Date;
// Test class
public class DateUtilsDemo {
public static void main(String[] args) throws ParseException {
// Create date object
Date d = new Date();
String s1 = DateUtils.dataToString(d, "yyyy year MM month dd Japan HH:mm:ss");
System.out.println(s1);
String s2 = DateUtils.dataToString(d, "yyyy year MM month dd Japan ");
System.out.println(s2);
String s3 = DateUtils.dataToString(d, "HH:mm:ss");
System.out.println(s3);
System.out.println("------------");
String s = "2025-06-29 11:20:00";
Date dd = DateUtils.stringToDate(s, "yyyy-MM-dd HH:mm:ss");
System.out.println(dd);
}
}
2.5Calendar class ( application )
Calendar Class Overview
Calendar Some methods are provided for the conversion between a specific moment and a set of calendar fields , And provides some methods for operating calendar fields
Calendar Provides a class method getInstance Used to get generally useful objects of this type .
This method returns a Calendar object .
Its calendar fields have been initialized with the current date and time :Calendar rightNow = Calendar.getInstance();
Calendar Class common methods
Method name explain public int get(int field) Returns the value of the given calendar field public abstract void add(int field, int amount) According to calendar rules , Add or subtract the given calendar field... From the specified amount of time public final void set(int year,int month,int date) Set the month, year and day of the current calendar Sample code
public class CalendarDemo { public static void main(String[] args) { // Get calendar class object Calendar c = Calendar.getInstance(); //public int get(int field): Returns the value of the given calendar field int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH) + 1; // Because the month is from 0 Start , So calculate the month to +1 int date = c.get(Calendar.DATE); System.out.println(year + " year " + month + " month " + date + " Japan "); //public abstract void add(int field, int amount): According to calendar rules , Add or subtract the given calendar field... From the specified amount of time // demand 1:3 Years ago today // c.add(Calendar.YEAR,-3); // year = c.get(Calendar.YEAR); // month = c.get(Calendar.MONTH) + 1; // date = c.get(Calendar.DATE); // System.out.println(year + " year " + month + " month " + date + " Japan "); // demand 2:10 Years later, 10 Days ago, // c.add(Calendar.YEAR,10); // c.add(Calendar.DATE,-10); // year = c.get(Calendar.YEAR); // month = c.get(Calendar.MONTH) + 1; // date = c.get(Calendar.DATE); // System.out.println(year + " year " + month + " month " + date + " Japan "); //public final void set(int year,int month,int date): Set the month, year and day of the current calendar c.set(2050,10,10); year = c.get(Calendar.YEAR); month = c.get(Calendar.MONTH) + 1; date = c.get(Calendar.DATE); System.out.println(year + " year " + month + " month " + date + " Japan "); } }
2.6 February day case ( application )
Case needs
Get the number of days in February of any year
Code implementation
public class CalendarTest { public static void main(String[] args) { // Keyboard entry any year Scanner sc = new Scanner(System.in); System.out.println(" Please enter year :"); int year = sc.nextInt(); // Sets the year of the calendar object 、 month 、 Japan Calendar c = Calendar.getInstance(); c.set(year, 2, 1); //3 month 1 Push forward one day , Namely 2 Last day of the month c.add(Calendar.DATE, -1); // Just get the output of this day int date = c.get(Calendar.DATE); System.out.println(year + " Year of 2 Month has " + date + " God "); } }
3. abnormal
3.1 abnormal ( memory )
Overview of exceptions
An exception is an abnormal condition in the program
Abnormal architecture
3.2JVM The default way to handle exceptions ( understand )
If something goes wrong with the program , We didn't do anything , Final JVM Will do the default processing , The processing method has the following two steps :
Name the exception , The error reason and the location of the exception are output on the console
Program stop
3.3try-catch Handle exceptions in different ways ( application )
Define format
try { Code with possible exception ; } catch( Exception class name Variable name ) { Exception handling code ; }
Execute the process
- The program from try The code inside starts to execute
- Something unusual happened , Will jump to the corresponding catch Go inside and do it
- After execution , The program can continue to execute
Sample code
public class ExceptionDemo01 { public static void main(String[] args) { System.out.println(" Start "); method(); System.out.println(" end "); } public static void method() { try { int[] arr = { 1, 2, 3}; System.out.println(arr[3]); System.out.println(" Can you access it here "); } catch (ArrayIndexOutOfBoundsException e) { // System.out.println(" The array index you accessed does not exist , Please go back and modify it to the correct index "); e.printStackTrace(); } } }
3.4Throwable Member method ( application )
Common methods
Method name explain public String getMessage() Back here throwable The detailed message string for public String toString() Returns a short description of this throw public void printStackTrace() Output the abnormal error message to the console Sample code
public class ExceptionDemo02 { public static void main(String[] args) { System.out.println(" Start "); method(); System.out.println(" end "); } public static void method() { try { int[] arr = { 1, 2, 3}; System.out.println(arr[3]); //new ArrayIndexOutOfBoundsException(); System.out.println(" Can you access it here "); } catch (ArrayIndexOutOfBoundsException e) { //new ArrayIndexOutOfBoundsException(); // e.printStackTrace(); //public String getMessage(): Back here throwable The detailed message string for // System.out.println(e.getMessage()); //Index 3 out of bounds for length 3 //public String toString(): Returns a short description of this throw // System.out.println(e.toString()); //java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 //public void printStackTrace(): Output the abnormal error message to the console e.printStackTrace(); // java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 // at com.itheima_02.ExceptionDemo02.method(ExceptionDemo02.java:18) // at com.itheima_02.ExceptionDemo02.main(ExceptionDemo02.java:11) } } }
3.5 The difference between compile time and run time exceptions ( memory )
Compile time exception
- All are Exception Classes and subclasses
- Processing must be displayed , Otherwise, the program will have an error , Unable to compile
Runtime exception
- All are RuntimeException Classes and subclasses
- No display processing is required , You can also handle the same as compile time exceptions
3.6throws Handle exceptions in different ways ( application )
Define format
public void Method () throws Exception class name { }
Sample code
public class ExceptionDemo { public static void main(String[] args) { System.out.println(" Start "); // method(); try { method2(); }catch (ParseException e) { e.printStackTrace(); } System.out.println(" end "); } // Compile time exception public static void method2() throws ParseException { String s = "2048-08-09"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date d = sdf.parse(s); System.out.println(d); } // Runtime exception public static void method() throws ArrayIndexOutOfBoundsException { int[] arr = { 1, 2, 3}; System.out.println(arr[3]); } }
matters needing attention
- This throws The format follows the parentheses of the method
- Compile time exceptions must be handled , Two treatment schemes :try…catch … perhaps throws, If the throws This program , Who will call who will handle
- Run time exceptions can be ignored , When something goes wrong , We need to come back and modify the code
3.7throws and throw The difference between ( memory )
throws
Used after method declaration , With the exception class name
Means throw an exception , Handled by the caller of the method
Represents a possibility of an exception , These exceptions do not necessarily occur
throw
Used in method body , Followed by the exception object name
Means throw an exception , Handled by statements inside the method
perform throw Must have thrown some kind of exception
3.8 Custom exception ( application )
If Java The built-in exception type provided does not meet the requirements of programming , At this time, we can design our own Java Class library or framework , This includes exception types . The implementation of custom exception class needs to inherit Exception Class or its subclasses , If the custom runtime exception class needs to inherit RuntimeException Class or its subclasses .
The syntax form of the custom exception is :
< Custom exception name >
In terms of coding specification , Generally, the class name of the custom exception class is XXXException, among XXX Used to represent the role of the exception .
Custom exception classes generally contain two construction methods : One is the default construction method without parameters , Another constructor receives a custom exception message as a string , And pass the message to the constructor of the superclass .
for example , The following code creates a file named IntegerRangeException Custom exception class for :
class IntegerRangeException extends Exception {
public IntegerRangeException() {
super();
}
public IntegerRangeException(String s) {
super(s);
}
}
The custom exception class created by the above code IntegerRangeException Class inherits from Exception class , There are two constructors in this class .
Custom exception classes
public class ScoreException extends Exception { public ScoreException() { } public ScoreException(String message) { super(message); } }
The teacher class
public class Teacher { public void checkScore(int score) throws ScoreException { if(score<0 || score>100) { // throw new ScoreException(); throw new ScoreException(" You gave the wrong score , The score should be 0-100 Between "); } else { System.out.println(" Normal performance "); } } }
Test class
public class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(" Please enter the score :");
int score = sc.nextInt();
Teacher t = new Teacher();
try {
t.checkScore(score);
} catch (ScoreException e) {
e.printStackTrace();
// Or is it e.getMessage();
}
}
}
边栏推荐
- LeetCode 1189. Maximum number of "balloons"
- LeetCode 8. String conversion integer (ATOI)
- Classical concurrency problem: the dining problem of philosophers
- FFT 学习笔记(自认为详细)
- 7.5 simulation summary
- N1 # if you work on a metauniverse product [metauniverse · interdisciplinary] Season 2 S2
- Shardingsphere source code analysis
- JS 这次真的可以禁止常量修改了!
- FPGA内部硬件结构与代码的关系
- Room cannot create an SQLite connection to verify the queries
猜你喜欢
FFmpeg学习——核心模块
FFMPEG关键结构体——AVCodecContext
Atcoder beginer contest 254 [VP record]
Search (DFS and BFS)
notepad++正則錶達式替換字符串
wx. Getlocation (object object) application method, latest version
[noi simulation] Anaid's tree (Mobius inversion, exponential generating function, Ehrlich sieve, virtual tree)
Single merchant v4.4 has the same original intention and strength!
Browser local storage
Doppler effect (Doppler shift)
随机推荐
Global and Chinese markets for hinged watertight doors 2022-2028: Research Report on technology, participants, trends, market size and share
权限问题:source .bash_profile permission denied
About the slmgr command
AtCoder Beginner Contest 254【VP记录】
Recognize the small experiment of extracting and displaying Mel spectrum (observe the difference between different y_axis and x_axis)
How to solve the problems caused by the import process of ecology9.0
XML配置文件
[designmode] Decorator Pattern
Uniapp development, packaged as H5 and deployed to the server
Key structure of ffmpeg - avformatcontext
Tools to improve work efficiency: the idea of SQL batch generation tools
硬件及接口学习总结
从底层结构开始学习FPGA----FIFO IP核及其关键参数介绍
如何解决ecology9.0执行导入流程流程产生的问题
【线上小工具】开发过程中会用到的线上小工具合集
Miaochai Weekly - 8
2022-02-13 work record -- PHP parsing rich text
Chapter 16 oauth2authorizationrequestredirectwebfilter source code analysis
Power Query数据格式的转换、拆分合并提取、删除重复项、删除错误、转置与反转、透视和逆透视
Codeforces gr19 D (think more about why the first-hand value range is 100, JLS yyds)