Dark Horse programmer _ Java exception common Java Library Class, dark horse _ java

Source: Internet
Author: User

Dark Horse programmer _ Java exception common Java Library Class, dark horse _ java
Java exception 1: Basic concepts of exceptions

Exceptions are a type of command flow that causes program interruption. They are abnormal during runtime. in Java, all exceptions follow the object-oriented design philosophy, all exceptions exist in the form of objects and classes.

2. Inheritance structure of exception classes

In the Exception structure of Java, there are actually two most common classes, Exception and Error, which are the subclasses of Throwable.

Exception: Generally, it indicates a problem in the program. You can use try... catch to handle it directly.

Error: Generally, it is a JVM Error that cannot be processed in the program.

3. Java Exception Handling Mechanism

Steps for Processing Based on the object-oriented thinking

(1) Once an exception occurs, an instantiated object of the exception class will be generated first.

(2) Capture exception classes in try statements

(3) The generated exception object matches the exception types in the catch statement. If the matching succeeds, the code in the catch statement is executed.

Capture of exception handling:
This is a targeted way to handle exceptions.
Specific format:
Try {
// Code to detect exceptions.
} Catch (exception variable) {// This variable is used to accept the exception object
// Code for handling exceptions.
} Finally {
// Code that will be executed
}

Try catch finally code block combination features
(1) try catch finally
(2) try catch (pair) when there is no need to release resources, you do not need to define finally
(3) A try finally exception cannot be directly caught, but the resource must be closed.

According to the polymorphism of the object, all subclass instances can be accepted by the parent class, so the upward transformation concept can be used. make all Exception objects accept exceptions. in Java, all exceptions with a small capture range must be placed before exceptions with a large capture range, otherwise, an error occurs during compilation. (If the capture range is large, it should be placed at the end)

Throws: Used in functions, it throws exception classes, can throw multiple, separated by commas
Throw: the internal part of the function used throws an exception object.

Exception Handling principles:
(1) If the function throws an exception to be detected, it must be declared on the function,
Otherwise, you must use trycatch to capture data within the function. Otherwise, compilation fails.
(2) If you call a function that declares an exception, either trycatch or throws. Otherwise, the compilation fails.
(3) When to catch and throws?
Internal functions can solve catch and cannot solve the problem. throws can be used to notify the caller to solve the problem.
(4) If one function throws a pair of exceptions, multiple catch methods are used for targeted processing.

Since Throwable is the largest class in exceptions, can it be used directly to catch all exceptions?

It is not recommended to use this method. The Exception can only be captured at the maximum, because in Threowable, it has two subclasses. The Error itself does not need to be processed by the program, but the Exception must be handled by the program, therefore, Throwable is not necessary. For another program, it is best to capture multiple exceptions separately, instead of directly capturing all exceptions using exceptions.

3. Applications of throw and throws
Package cn. wjd. exception; class Math {public int div (int x, int y) throws Exception {int temp = 0; System. out. println ("... computing starts... "); try {temp = x/y;} catch (Exception e) {throw e;} finally {System. out. println ("... computing ends... ");} return temp;} public class ThrowDemo {public static void main (String [] args) {Math m = new Math (); try {m. div (10, 0);} catch (Exception e) {System. out. println ("... exception... "+ e );}}}

In the above Code, no matter whether the div () in the Math class encounters an exception, the "computing end" statement will be executed. If an exception occurs, the exception will be handed over to the caller for processing.

 

4. Exception class and RuntimeException class

Exception: try... catch must be used in the program for processing.

RuntimeException: try... catch is not used for processing. However, if an exception occurs, the exception is handled by JVM.

5. finally is used in database operations. This keyword is very useful and used to close the database connection.

Class NoDateException extends Exception {

}
Void addDate (Date d) throws NoDateException {
Try {
An exception occurred while adding data. SQLException exception occurred.
This exception should be handled internally. If it is not thrown out, addDate does not know the SQL database exception. At this time
An exception type is defined for data that has not been added successfully.
} Catch (SQLException e ){
Throw new NoDateException ();

} Finally {
Close Database

}
}

 

Java Common Library Class 1, System class

The System class is a collection of System-related attributes and methods, and all attributes and methods in the System are static.

package cn.wjd.system;public class SystemDemo2 {    public static void main(String[] args) {        System.getProperties().list(System.out);    }}
java.runtime.name=Java(TM) SE Runtime Environmentsun.boot.library.path=D:\jdk\jdk1.7.0_45\jre\binjava.vm.version=24.45-b08java.vm.vendor=Oracle Corporationjava.vendor.url=http://java.oracle.com/path.separator=;java.vm.name=Java HotSpot(TM) Client VMfile.encoding.pkg=sun.iouser.script=user.country=CNsun.java.launcher=SUN_STANDARDsun.os.patch.level=Service Pack 1java.vm.specification.name=Java Virtual Machine Specificationuser.dir=D:\workspace\OtherApijava.runtime.version=1.7.0_45-b18java.awt.graphicsenv=sun.awt.Win32GraphicsEnvironmentjava.endorsed.dirs=D:\jdk\jdk1.7.0_45\jre\lib\endorsedos.arch=x86java.io.tmpdir=C:\Users\ADMINI~1\AppData\Local\Temp\line.separator=java.vm.specification.vendor=Oracle Corporationuser.variant=os.name=Windows 7sun.jnu.encoding=GBKjava.library.path=D:\jdk\jdk1.7.0_45\bin;C:\Windows\Sun...java.specification.name=Java Platform API Specificationjava.class.version=51.0sun.management.compiler=HotSpot Client Compileros.version=6.1user.home=C:\Users\Administratoruser.timezone=java.awt.printerjob=sun.awt.windows.WPrinterJobfile.encoding=GBKjava.specification.version=1.7user.name=Administratorjava.class.path=D:\workspace\OtherApi\binjava.vm.specification.version=1.7sun.arch.data.model=32java.home=D:\jdk\jdk1.7.0_45\jresun.java.command=cn.wjd.system.SystemDemo2java.specification.vendor=Oracle Corporationuser.language=zhawt.toolkit=sun.awt.windows.WToolkitjava.vm.info=mixed mode, sharingjava.version=1.7.0_45java.ext.dirs=D:\jdk\jdk1.7.0_45\jre\lib\ext;C:\Win...sun.boot.class.path=D:\jdk\jdk1.7.0_45\jre\lib\resources....java.vendor=Oracle Corporationfile.separator=\java.vendor.url.bug=http://bugreport.sun.com/bugreport/sun.cpu.endian=littlesun.io.unicode.encoding=UnicodeLittlesun.desktop=windowssun.cpu.isalist=pentium_pro+mmx pentium_pro pentium+m...

The above lists all the environment attributes of the local machine using System. There are two points to note in the above attributes.

(1) default file encoding: file. encoding = GBK

(2) file delimiter: file. separate = \

 

 

2. Date operations

In Java, it provides good support for date operations, mainly using java. in the util package, Date, Calendar, and java. simpleDateFormat in the text package. The following are some knowledge points about date operations.

(1) Date class

The Date class is a relatively simple Date class. It can obtain a complete time by using its default constructor,
 

package cn.wjd.system;import java.util.Date;public class DateDemo02 {    public static void main(String[] args) {        Date date = new Date();        System.out.println(date);//Wed Jul 23 13:53:52 CST 2014    }}

The above code has obtained the accurate time of the current system, but this format does not conform to the date format we see in daily life. Therefore, if you need to display the time in your own format, use the Calendar class to complete the operation.

(2) Calendar class

This class is an abstract class, which can accurately obtain the time to milliseconds. This class has a method to obtain an object of this class.

Package cn. wjd. system; import java. util. calendar; public class CalendarDemo {public static void main (String [] args) {Calendar c = Calendar ar. getInstance (); int year = c. get (Calendar. YEAR); int month = c. get (Calendar. MONTH) + 1; int day = c. get (Calendar. DAY_OF_MONTH); int week = c. get (Calendar. DAY_OF_WEEK); System. out. println (week); System. out. println (year + "year" + month + "month" + day + "day" + getWeek (week);} public static String getWeek (int week) {String [] weeks = {"", "Sunday", "1 week", "2 weeks", "3 days", "4 days", "5 days ", "6 weeks"}; return weeks [week];}(3) DateFormat class

This class is used to format the time and convert it to a date format that is more in line with Chinese habits. This class is also an abstract class, but it provides a static method, you can directly obtain instances of this class.

Both the DateFormat and MessageFormat classes belong to the subclass of the Format class. They are used specially for formatting data.

Package cn. wjd. system; import java. text. dateFormat; import java. text. parseException; import java. text. simpleDateFormat; import java. util. date; public class DateDemo {public static void main (String [] args) throws ParseException {// methodDemo_1 (); methodDemo_2 (); // methodDemo_3 ();} /** use the parse method in DateFormat */public static void methodDemo_3 () throws ParseException {String str_date = "2013-11-11 "; dateFormat dateFormat = DateFormat. getDateInstance (); Date date = dateFormat. parse (str_date); System. out. println (date );} /** format the date object * use the constructor in Date to set the date object MM> Date object through setTime * you can use the method in the date object to set the field (year, month, day, etc.) to operate 2 Date objects --> millisecond value getTime Method * can be calculated using a millisecond value through a specific value */private static void methodDemo_1 () {long time = System. currentTimeMillis (); System. out. println (time); // 1404527032257 Date date = new Date (); // the current Date and time are encapsulated into the object System. out. println (date); // Sat Jul 05 10:25:13 CST 2014 Date date2 = new Date (1404527032257l); // encapsulate the specified millisecond value into the object System. out. println (date2 );}}
(4) SimpleDateFormat class

This class is used to convert a date format to another date format. It is not an abstract class and can be instantiated.

Package cn. wjd. system; import java. text. parseException; import java. text. simpleDateFormat; import java. util. date; public class SimpleDateDemo {public static void main (String [] args) throws ParseException {String strDate = "2009-1-2 1-2 11:11:11"; String part1 = "yyyy-MM-dd HH: mm: ss "; String part2 =" yyyy MM mm dd hh mm mm ss sec "; SimpleDateFormat sdf1 = new SimpleDateFormat (part1); SimpleDateFormat sdf2 = new SimpleDateFormat (part2 ); date d = new Date (); d = sdf1.parse (strDate); // extract the Date from the given String newDate = sdf2.format (d ); // convert the date to the new format System. out. println (newDate );}}

In the above Code, first use the first template to extract the date numbers in the string, and then use the second template to convert these date numbers into new formats for representation.

The SimpleDateFormat class is often used to convert String to Date type data.

In actual development, each data input by the user is accepted as a String. Therefore, SimpleDateFormat can be used to convert String to Date data correctly.

package cn.wjd.system;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class SimpleDateFormatDemo {    public static void main(String[] args) throws ParseException {        String str = "2011-11-11 11:11:11";        String part ="yyyy-MM-dd HH:mm:ss";        SimpleDateFormat sdf = new SimpleDateFormat(part);        Date d = sdf.parse(str);        System.out.println(d);//Fri Nov 11 11:11:11 CST 2011    }}

The above code converts a Date of the String type to the data of the Date type. I guess this will be frequently used in future databases.


Java programmers generally have their own toolkit, such as some common class libraries, and common methods ......

What do you mean by that?
The common class library is also the API, which is included when JDK is installed. You do not need to download it separately.
You only need to download the JDK installation program from the official website.

The company wants to recruit JAVA programmers to access other java programs, such as databases.

Generally, java programmers do not have high database requirements or database requirements. The most important thing about the database is the design and SQL optimization, which is irrelevant to the language.
For web applications, we should actually focus on servlet, understand the http protocol, and learn any framework without coming up. The framework is actually very simple.
In addition, you should be familiar with js, html, and css.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.