Java starts from scratch (exception), java starts from scratch

Source: Internet
Author: User

Java starts from scratch (exception), java starts from scratch
1. What is an exception?

Literally, an exception is an abnormal reality.

Exceptions in the program also occur occasionally only when the program is running. If the program is not running, an error is reported during compilation. This is not an exception, but a compilation error, which is usually a syntax error.

2. Exceptions in java

Java provides two main types of exceptions: runtime exception and checked exception. All checked exceptions are derived from the java. lang. exception class, while
Runtime exception is derived from the java. lang. RuntimeException or java. lang. Error class. Their differences are manifested in two aspects: Mechanism and logic.

All exceptions must be handled! An exception can be thrown in the program, but the exception cannot be thrown to the end user.
Bugs are not bugs in the hands of programmers, but once delivered, they are bugs.

2.1. Mechanism

Runtime exceptions:

  • A runtime exception is thrown if no declaration is required during method definition.
  • You do not need to capture this runtime exception when calling this method.
  • Runtime exception is from java. lang. RuntimeException or
  • Derived from the java. lang. Error class.

Checked exceptions:

  • When defining a method, you must declare all possible checked exceptions.
  • When calling this method, you must capture its checked exception. Otherwise, you must
  • Pass its exception
  • Checked exception is derived from the java. lang. Exception class.
2.2 logically

Logically, checked exceptions and runtime exception have different purposes.

Checked exception indicates an exception that can be directly handled by the caller. Checked exception forces you to capture it and handle this exception.

Runtime exception indicates a program error that the caller cannot handle or recover.

3. Exceptions in the program 3.1. Example 1
Package com. pb. demo6; import java. util. operator;/** calculate the quotient of two integers * how the program handles the exception */public class Test1 {public static void main (String [] args) {// obtain input records input = new records (System. in); System. out. println ("Enter dividend:"); int num1 = input. nextInt (); System. out. println ("Enter the divisor:"); int num2 = input. nextInt (); int result = num1/num2; System. out. println (num1 + "and" + num2 + "OPERATOR:" + result );
System. out. println ("Thank you! ");}}

When the input divisor is not 0, it runs normally, but when the input divisor is 0 or a string, an exception is reported:

Please input divisor: 2 Please input divisor: 0 Exception in thread "main" java. lang. ArithmeticException:/by zero at com. pb. demo6.Test1. main (Test1.java: 18)
Enter the divisor: ffdException in thread "main" java. util. InputMismatchException

At the same time, when an exception occurs, the final output statement is not executed.

Iv. Common exceptions

Java. lang. ArithmeticExecption
Arithmetic exception class. This exception is thrown when an operation condition is abnormal. For example, if an operation such as "divide by zero" occurs in the program, this exception occurs. For this exception, you should check whether the formula is inappropriate when it involves mathematical operations in your program.

Java. lang. NullPointerException
Null Pointer exception class. Simply put, an uninitialized object or non-existent object is called. This exception is thrown when an application tries to use null where an object is needed:

  • Call the instance method of a null Object
  • Access or modify null object fields
  • Use null as an array to obtain its length.
  • Use null as an array to access or modify its time slice.
  • Throw null as the Throwable Value

The application should throw an instance of this class to indicate that other null objects are used illegally.

Java. lang. ClassNotFoundException
Class exception not found. This exception is thrown when an application attempts to load a class using a string name using the following method:

  • ForName method in Class
  • The findSystemClass method in the ClassLoader class
  • LoadClass method in ClassLoader class

Java. lang. ArrayIndexOutOfBoundsException
An error occurred while crossing the array subscript. An exception thrown when an invalid index is used to access an array. If the index is negative or greater than or equal to the array size, the index is invalid.
Currently, most programs operate on arrays. Therefore, when calling arrays, you must carefully check whether the subscript you call exceeds the range of arrays. Generally, it is not easy to call the display (that is, directly using a constant as a subscript), but the implicit (that is, using a variable to represent a subscript) call often causes errors, the length of the array defined in the program is determined by some specific methods, not stated in advance. At this time, it is best to first check the length of the array to avoid this exception.

Java. lang. IllegalArgumentException
Method parameter error. The thrown exception indicates that an invalid or incorrect parameter is passed to the method.
The method in the class library may cause such an error in some situations, such as the volume parameter in the volume adjustment method. If it is written as a negative number, this exception occurs, for example, g. setColor (int red, intgreen, int blue) three values in this method, if there is more than 255, this exception will also occur, so once this exception is found, what we need to do, check whether the parameter passing in the method call is incorrect.

Java. lang. IllegalAccessException
No access permission exception. When an application attempts to create an instance (instead of an array), set or retrieve a field, or call a method, however, if the currently executed method cannot access the definition of a specified class, field, method, or constructor, this exception is thrown when a package is used in the program.

Java. lang. IncompatibleClassChangeError
Incompatible class change error. When the class definition on which the method being executed depends is incompatible, this error is thrown when the Declaration definition of some classes in the application is modified, this error is easily caused when the entire application is not re-compiled and runs directly.

Java. lang. InstantiationError
Instantiation error. When an application attempts to instantiate an abstract class or an interface using the new structure of Java, this exception is usually caught by the compiler. If there are incompatible changes in the class definition, this error occurs.
Will only happen at runtime

Java. lang. LinkageError
Link error. This error and all its subclasses indicate that a class depends on another class to a certain extent. However, after the previous class is compiled, the latter class changes incompatible.

Java. lang. StackOverflowError
Stack overflow error. This error is thrown when the hierarchy of recursive calls of an application is too deep, leading to stack overflow.

Java. lang. NumberFormatException
The number format is incorrect. This exception is thrown when you try to convert a String to a specified numeric type that does not meet the numeric type requirements.

Java. lang. RuntimeException
Exception during running. RuntimeException is any subclass of RuntimeException that may be thrown during the normal operation of the Java Virtual Machine During method execution but is not captured, and does not need to be declared in the throws clause.

Java. io. IOException
Input/Output exceptions. This exception is thrown when an I/O exception occurs. This is a common exception generated by failed or interrupted I/O operations.

Java. io. FileNotFoundException
File not found. This exception is thrown when an attempt to open a file indicated by a specified path name fails.
If a file with the specified path name does not exist, this exception is thrown by the FileInputStream, FileOutputStream, and RandomAccessFile constructor. If the file exists but cannot be accessed for some reason, such as trying to open a read-only file for writing, these constructor will still throw this exception

Java. io. EOFException
An error occurred while the file has ended. This exception is thrown when the end of a file or stream is accidentally reached during the input process.
This exception is mainly used by the data input stream to indicate that it reaches the end of the stream. Note that many other input operations return a special value to reach the end of the stream, instead of throwing an exception.

Java. lang. InterruptedException
Aborted exception. When a thread is in the waiting, sleep, or occupying status before or during the activity and the thread is interrupted, this exception is thrown. Sometimes, one method may be desired, test whether the current thread has been interrupted. If the thread has been interrupted, this exception is thrown immediately.

V. Exception Handling 5.1. Syntax:
Try {// statements that may cause exceptions} catch (exception-type exception object) {// write Exception Handling statements} [catch (exception-type exception object) {// write an exception handling statement} catch (exception-type exception object) {// write an exception handling statement }.... ] [Finally {program code that will certainly run ;}

Mainly used in combination: try-catch, try-catch-finally, and try-finally

5.2. Multiple exceptions

If multiple catch blocks exist at the same time, the Exception must be placed in the last catch block.

Package com. pb. demo6; import java. util. inputMismatchException; import java. util. export; import javax. naming. authenticationException;/** calculate the quotient of two integers * how the program handles the exception */public class Test1 {public static void main (String [] args) {// obtain the input from the keyboard. try {inputs input = new inputs (System. in); System. out. println ("Enter dividend:"); int num1 = input. nextInt (); System. out. println ("Enter the divisor:"); int num2 = input. nextInt (); int result = n Um1/num2; System. out. println (num1 + "and" + num2 + "OPERATOR:" + result);} catch (InputMismatchException e) {System. out. println ("the input is not a number"); e. printStackTrace ();} catch (ArithmeticException e) {System. out. println ("the divisor cannot be 0"); e. printStackTrace ();} catch (Exception e) {System. out. println ("other errors! "); E. printStackTrace () ;}finally {System. out. println (" Thank you! ");}}}
Please input divisor: 2 Please input divisor: 0 divisor cannot be 0java. lang. ArithmeticException:/by zero at com. pb. demo6.Test1. main (Test1.java: 22) Thank you!

Statements in finally are executed no matter the exception occurs.

However, if the catch Block contains: Execute System. exit (0); orSystem. exit (-1); the program will end directly, and the statements in finally will not be executed.

5.3. Java's exception handling mechanism is actually handled in an object-oriented manner throughout java's exception handling process. The process steps are as follows:
  • Once an exception occurs, an instantiated object of the exception class is first generated;
  • Capture the exception object in the try statement;
  • The generated exception object matches each exception type in the catch statement. If the matching succeeds, the code in the catch statement is executed.

6. Throw an exception 6.1. when defining a method, the throws keyword can be declared. The method declared by throws indicates that this method does not handle exceptions, instead, it is handed over to the call area of the method for processing. Throws uses the public return value type method name (parameter list ...) Throws Exception{}
Package com. pb. demo6; import java. util. inputMismatchException; import java. util. export; import javax. naming. authenticationException;/** calculate the quotient of two integers * how the program handles the exception */public class Test2 {public static void main (String [] args) {try {divide ();} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace () ;}}// division Operation public static void divide () throws Exception {// obtain input records input = new records (System. in); System. out. println ("Enter dividend:"); int num1 = input. nextInt (); System. out. println ("Enter the divisor:"); int num2 = input. nextInt (); int result = num1/num2; System. out. println (num1 + "and" + num2 + "OPERATOR:" + result );}}
6.2. The throw keyword is different from throws. throw can be directly used to throw an exception. When thrown, you can directly throw the instantiated object of the exception class.
Package com. pb. demo6;/** human */public class Person {private String name; private String sex; private int age; public String getName () {return name ;} public void setName (String name) {this. name = name;} public String getSex () {return sex;} public void setSex (String sex) throws Exception {if (sex. equals ("male") | sex. equals ("female") {this. sex = sex;} else {throw new Exception ("gender can only be male or female");} publ Ic int getAge () {return age;} public void setAge (int age) {if (age >=0 & age <= 150) {this. age = age;} else {try {throw new Exception ("age can only be between 0 and 50 years old! ");} Catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace () ;}} public void printSelf () {System. out. println ("name:" + this. name + "Gender:" + this. sex + "Age:" + this. age );}}
Package com. pb. demo6; public class PersonTest {public static void main (String [] args) {Person p = new Person (); try {p. setName ("Zhang San"); p. setSex ("male"); p. setAge (200); p. printSelf ();} catch (Exception e) {e. getMessage (); e. printStackTrace ();}}}
7. Custom exceptions a large number of exception classes have been provided in Java, but these exception classes sometimes cannot meet developers' requirements, therefore, you can define your own Exception classes according to your needs and define the Exception classes. You only need to inherit the Exception classes. Of course, it can inherit other types, such as Exception, Throwable, RuntimeException, and its subclass, including Exception, Throwable, and effect, if you do not require the caller to handle the thrown exception, you can inherit the RuntimeException and its subclass calls and only need to throw new custom exception name (information)
package com.pb.demo6;public class MyException extends Exception {    public MyException() {        super();        // TODO Auto-generated constructor stub    }    public MyException(String message, Throwable cause,            boolean enableSuppression, boolean writableStackTrace) {        super(message, cause, enableSuppression, writableStackTrace);        // TODO Auto-generated constructor stub    }    public MyException(String message, Throwable cause) {        super(message, cause);        // TODO Auto-generated constructor stub    }    public MyException(String message) {        super(message);        // TODO Auto-generated constructor stub    }    public MyException(Throwable cause) {        super(cause);        // TODO Auto-generated constructor stub    }           }
Package com. pb. demo6;/** human */public class Person {private String name; private String sex; private int age; public String getName () {return name ;} public void setName (String name) {this. name = name;} public String getSex () {return sex;} public void setSex (String sex) throws Exception {if (sex. equals ("male") | sex. equals ("female") {this. sex = sex;} else {throw new MyException ("gender can only be male or female");} pu Blic int getAge () {return age;} public void setAge (int age) {if (age> = 0 & age <= 150) {this. age = age;} else {try {throw new MyException ("age can only be between 0 and 50 years old! ");} Catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace () ;}} public void printSelf () {System. out. println ("name:" + this. name + "Gender:" + this. sex + "Age:" + this. age );}}
Package com. pb. demo6; public class PersonTest {public static void main (String [] args) {Person p = new Person (); try {p. setName ("Zhang San"); p. setSex ("male"); p. setAge (200); p. printSelf ();} catch (Exception e) {e. getMessage (); e. printStackTrace ();}}}

Com. pb. demo6.MyException: gender can only be male or female

The obtained exception is our custom exception.

 

Related Article

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.