Java Programming Basics-Abnormal __ algorithm

Source: Internet
Author: User
Tags arithmetic array length finally block getmessage instance method throw exception throwable
First, abnormal 1, what is abnormal In Java, when the program is running in the abnormal situation is called an exception, in the form of exception classes to encapsulate these abnormal conditions, through the exception handling mechanism for the operation of the various problems occurred in the process. In fact, Java is the description of the abnormal situation after the object embodiment.
2. Java Exception class

A large number of exception classes are provided in Java, and the Throwable class is a superclass of all errors or exceptions in the Java language, looking up the API documentation. An object can be thrown through either a Java virtual machine or a Java throw statement only if it is an instance of this class (or one of its subclasses). Similarly, only one of this class or its subclasses can be a parameter type in a catch clause.

Throwable has two direct subclass error and exception, in which error represents errors generated in the program, exception represents the exception generated in the program.

A the error class is called The Fault class, which indicates that the system internal error or resource exhaustion error generated by the Java runtime is more serious and cannot be resumed by modifying the program itself. For error generally do not write targeted code to deal with it.
b The Exception class, called an exception class, represents an error that the program itself can handle, and exception handling in the Java Development program is for the exception class and its subclasses. There is a special RuntimeException class in many subclasses of the exception class, and its subclasses are used to represent run-time exceptions, except that all other subclasses of the exception class are used to represent compile-time exceptions. For exception, it can be handled using targeted code.


3, Throwable common methods

String GetMessage (): Returns the detailed message string for this throwable

void Printstacktrace (): Outputs this throwable and its trace to the standard error stream
void Printstacktrace (PrintStream s): Outputs this throwable and its trace to the specified output stream


4, common anomalies RuntimeException Subclass:

A) java.lang.ArrayIndexOutOfBoundsException

array subscript out of bounds exception. Thrown when the index value of an array is negative or greater than or equal to the size of the array.

b) java.lang.ArithmeticException
Arithmetic condition exception. For example: integers except 0.

c) java.lang.NullPointerException
Null pointer exception. The exception is thrown when an application attempts to use null where the object is required. For example, invoking an instance method of a null object, accessing the properties of a null object, calculating the length of a null object, throwing null with the throw statement, and so on
D) java.lang.ClassNotFoundException
The class exception was not found. This exception is thrown when an application attempts to construct a class based on a class name in the form of a string, and when the class file of the corresponding name is not found after traversing Classpah.
e) java.lang.NegativeArraySizeException array length is a negative exception

f) java.lang.IllegalArgumentException illegal parameter anomaly

IOException a) IOException: An exception that may occur when manipulating input and output streams.
b) FileNotFoundException file not found exception

other a) ClassCastException type Conversion Exception class
b) SQLException operation database Exception class
c) Nosuchfieldexception field not found exception
D) The Nosuchmethodexception method did not find the thrown exception
e) NumberFormatException the string into the exception thrown by the number
f) Stringindexoutofboundsexception string index out of range thrown exception
g) Illegalaccessexception does not allow access to a class of exceptions



Second, run-time exceptions and compile-time exceptions

exceptions can be divided into compile-time detected exceptions, which, at compile time, fail if there is no processing (no throw or try). and compile-time exceptions that are not instrumented (Run-time exception runtimeexception and its subclasses). At compile time, no processing is required and the compiler does not check. )
1, compile-time exception (also known as checked exception)

Compile-time exceptions are characterized by a Java compiler that checks for exceptions that must be handled if an exception occurs, otherwise the program cannot compile. There are two ways to handle it: one is to use a try. The catch statement catches the exception, and the second is to throw an exception using the throws keyword declaration to let the caller handle it.
2, Run-time Anomaly (also known as unchecked exception)

The feature is that the Java compiler does not check it, and when such an exception occurs in the program, there is no immediate capture or throw processing, and the compilation can pass. Runtime exceptions are typically caused by a logical error in the program and cannot be recovered when the program is running.



III. mechanism of exception handling

in a Java application, handling of exceptions either throws an exception or catches an exception. Catch Exception 1, in Java, the exception is captured by the Try-catch statement. Its general grammatical form is:

       try {
             //program code
       &NBSP} Catch that may occur (ExceptionType1 e) {
            //captures and disposes of the exception type thrown by a try Type1
       &NBSP} catch (ExceptionType2 e) {
             //captures and disposes of the exception type Type2
        for a try Throw  }


Exception capture processing: A pair of curly braces after the keyword try packs a piece of code that may have an exception, called the monitoring area. An exception object is created when the Java method occurs during the run. Throwing exceptions out of the monitoring area, the Java Runtime system attempts to find a matching catch clause to catch the exception. A catch statement takes a parameter of type Throwable, indicating that the exception type can be caught. When an exception occurs in a try, the catch catches the exception that occurred, matches its own exception type, executes the code in the Catch block, and points the catch block argument to the thrown exception object. A catch statement can have multiple, matching an exception in multiple, and once the match is run its exception handling code, the Try-catch statement ends.
The principle of matching is that if the exception object thrown is an exception class for a catch clause, or a subclass of the exception class, the resulting exception object is considered to match the type of exception caught by the catch block.


2. Sample Demo:

Mathematically we all know that the divisor in division cannot be 0, and we take that as an example.

first, the case is demonstrated without any processing.

public class TestException {public

	static void Main (string[] args) {
		int x = 5;
		int y = 0;//divisor is 0
		System.out.println (x/y);

	}
}
the results of the operation are:

Exception in thread ' main ' java.lang.ArithmeticException:/by zero
At Test. Testexception.main (Testexception.java:8)

the system reported a arithmeticexception:/by zero arithmetic anomaly, and pointed out to be 0 apart


Second: We demonstrate that the catch throw statement throws a divisor of 0 and handles the exception.

public class TestException {public

	static void Main (string[] args) {
		int x = 5;
		int y = 0;//divisor is 0
		try {//monitor area
			if (y = = 0) {
				throw new ArithmeticException ();
				Throw exception via throw statement
			System.out.println (x/y);
		} catch (ArithmeticException e) {//catch exception
			SYSTEM.OUT.PRINTLN ("program exception, divisor cannot be 0");}
		}
the results of the operation are:

program exception, divisor cannot be 0


Simple analysis: In the try monitoring area through the IF statement to judge, when "divisor 0" error condition is set up to throw ArithmeticException exception, create ArithmeticException exception object, And by the throw statement to throw the exception to the Java runtime System, the system to find a matching exception handler catch and run the corresponding exception handling code, the printout of the program exception, divisor can not be 0, Try-catch statement, continue the program flow. In fact, the "divisor is 0" and so on ArithmeticException, is the Runtimexception subclass. Runtime exceptions are automatically thrown by the Run-time system and do not require the use of throw statements.


Finally, we test the capture runtime system to automatically throw a "divisor of 0" thrown ArithmeticException exception.

public class TestException {public

	static void Main (string[] args) {
		int x = 5;
		int y = 0;//divisor is 0
		try {
			System.out.println (x/y);
		} catch (ArithmeticException e) {//catch exception
			System.out.pri NTLN ("program exception, divisor cannot be 0");}
		}

the results of the operation are:

program exception, divisor cannot be 0


Simple analysis: There is a "divisor 0" error in the run, which throws a ArithmeticException exception. The runtime system creates an exception object and throws the monitoring area, which in turn matches the appropriate exception handler catch and executes the appropriate exception handling code. Because the cost of checking for run-time exceptions is much greater than the benefits of catching exceptions, runtime exceptions are not available. The Java compiler allows a run-time exception to be ignored, and a method can neither capture nor declare a Run-time exception.


Note: Once a catch catches a matching exception type, it enters the exception handling code. At the end of the process, it means that the entire Try-catch statement ends. Other catch clauses no longer have the opportunity to match and catch the exception type. For exception programs with multiple catch clauses, you should try to put the catch clause of the captured subclass exception in front of you, and try to put a catch clause that captures the parent class exception at the top of the hierarchy. Otherwise, catch clauses that capture the underlying subclass exception may be masked.
The runtimeexception exception class includes various common exceptions at run time, and the catch clause of the RuntimeException exception class should be put on the last side, or it may mask the subsequent specific exception handling or cause compilation errors.



3, Try-catch statement can also include the third part, is finally clause. It indicates what should be done, regardless of whether an exception occurs.

The general syntax for the

try-catch-finally statement is:
       try {
             //The program code
       &NBSP that can occur unexpectedly; catch (ExceptionType1 e) {
            // Catches and disposes of the exception type thrown by a try Type1
        } catch (ExceptionType2 e) {
             //captures and disposes of the exception type Type2
    for a try Throw      }finally{
             //the statement block
       &NBSP

that will execute regardless of whether an exception occurs

Finally block: The statements in the finally block are executed whether or not the exception is captured or handled. When a return statement is encountered in a try block or a catch block, the finally statement block is executed before the method returns. Finally blocks are not executed in the following 4 special cases:
1) An exception occurred in the finally statement block.
2 System.exit () exits the program in the previous code.
3 the thread in which the program is located dies.
4) Turn off the CPU.

code Example:

public class TestException {public

	static void Main (string[] args) {
		try {
			int result = Divide (4, 0);//Call Div IDE () method
			/int result = Divide (4, 2);//The test did not have an exception
			System.out.println (results);
		} catch (Exception e) {
			System.out.println ("Caught exception information is" + e.getmessage ());
		} finally {
			System.out.println ("Enter finally code block");
		}
		SYSTEM.OUT.PRINTLN ("program continues down execution");
	}

	public static int divide (int x, int y) defines a method for dividing two integers
	{
		int result = x/y;//Define a variable result remember the results of the
		division return R esult;//returns the result
	}
}
the results of the operation are:

The exception information captured is/by zero
Enter finally code block
Program continues down execution

the exception test result was not occurred:

2
Enter finally code block
Program continues down execution

Try, catch, finally three blocks of statements should be aware of the problem:
A try, catch, finally three block of statements can not be used alone, the three could be composed of try...catch...finally, Try...catch, try...finally three structure, catch statements can have one or more, Finally statement is up to one.

b The scope of the variables in try, catch, finally three blocks is within the code block, independent and inaccessible to each other. If you want to be accessible in three blocks, you need to define the variables outside the blocks.
c) When multiple catch blocks, only one of the exception classes is matched and the catch block code is executed, and no other catch blocks are executed, and the order of matching catch statements is from top to bottom.

d must follow the order in which the statement block placement order try-catch-finally.

e) can be nested try-catch-finally structure. For example, you can also have try in the try ... Catch handling


throw an exception 4. Throws throws an exception

If a method may have an exception, but does not have the ability to handle the exception, you can declare the thrown exception with the throws clause at the method declaration. For example, the car may malfunction during operation, the car itself can not handle the fault, so let the driver to deal with. The throws statement declares the type of exception to throw when the method is defined, and if the exception exception type is thrown, the method is declared to throw all exceptions. Multiple exceptions can be separated with commas. The syntax format for the throws statement is:

MethodName ([Param1,param2, ...]) Throws Exceptiontype1[,exceptiontype2 ...] {}
The throws keyword needs to be written after the method declaration, throws to declare the type of exception that occurred in the method, which is often referred to as a method declaration that throws an exception. After the exception is thrown to the caller by using the throws keyword, if the caller does not want to handle the exception, it can continue to throw up, but ultimately there is a caller who can handle the exception.

code Example:

public class TestException {public

	static void Main (string[] args) {
		try {
			int result = Divide (4, 0);
			SYSTEM.OUT.PRINTLN (result);
		} catch (ArithmeticException e) {
			System.out.println ("Caught exception information is" + e.getmessage ());
		} finally {
			System.out.println ("Enter finally code block");
		}
		SYSTEM.OUT.PRINTLN ("program continues down execution");
	}

	The public static int divide (int x, int y) throws arithmeticexception//throws an exception
	{
		int result = x/y;
		return result;
	}

throws throws exception rule: A If it is a Run-time exception, you can declare the exception to throw without using the throws keyword, and the compilation will still pass smoothly, but it will be thrown by the system at run time.
b if it is a compile-time exception, either catch it with a try-catch statement, or throw it with a throws clause declaration, or it will cause a compilation error

c) The caller of the method must either handle or throw back the exception only if an exception is thrown. When the caller of the method is powerless to handle the exception, it should continue to be thrown.


5. Throw an exception using throw

Throw always appears in the body of a function to throw a throwable type of exception. The program terminates immediately after the throw statement, the statement that follows it, and then the try block that contains the catch clause that matches it, in all the try blocks that contain it (possibly in the upper call function). Because the exception is an instance object of the exception class, we can create an instance object of the exception class that is thrown through the throw statement. The syntax format of the statement is:
throw new Exceptiontype ();

code Example:

public class MyException extends Exception {//Create custom exception class
	private String message;//define string type variable
	private int value; Defines the int type variable public

	myexception () {
		super ();
	}

	Public myexception (String, int value) {
		this.message = message;
		This.value = value;
	}

	public int GetValue () {return
		value;
	}

	Public String GetMessage () {return message
		;
	}
}
Test:
public class Testmyexception {public

	static void Main (string[] args) {

		try {//contains a statement that may have an exception result
			= divID E (4,-1);//Call Divide () method
			System.out.println (result);
		} catch (MyException e) {//Handle custom exception
			System.out.println (E.getmessage ());//output exception information
			System.out.println (negative number of error is: + E.getvalue ());/output exception value
		} catch ( ArithmeticException e) {//handling ArithmeticException exception
			System.out.println ("divisor cannot be 0")/output hint info
		} catch (Exception e) {//handling other exception
			System.out.println ("Other exceptions to the program");/output prompt information
		}
		System.out.println ("over");
	}

	public static int divide (int x, int y) throws myexception//definition method throws
	{
		if (Y < 0) {//judge parameter is less than 0
			throw new MyException ("There is a case where the divisor is negative.") ------/by Fushu ", y);//exception Information
		}
		return x/y;//returned value
	}
}
the results of the operation are:

A case where the divisor is negative is present. ------/by Fushu
Negative numbers for errors are:-1
Over

The difference between throws and throw:
A) throws is used on functions. Throw is used within functions.
b throws followed by the exception class, can be with multiple, separated by commas. Throw is followed by an exception object.


Iv. Custom Exceptions

because there are specific problems in the actual project, these problems are not described in Java and Encapsulate objects. So for these specific problems, you can follow Java's encapsulation of the problem. A custom exception package that is unique to the problem. Allow users to customize exceptions in Java, custom exception steps:
(1), create a custom exception class, and the class must inherit from exception or its subclasses. (Because the exception system has a feature because both the exception class and the exception object are thrown.) They all have the ability to be parabolic, which is a unique feature of the Throwable system. )
(2) The exception object is thrown through the throw keyword in the method.
(3), if the exception is handled in the current method of throwing an exception, you can use the Try-catch statement to catch and process it, otherwise, at the declaration of the method, the throws keyword indicates the exception to be thrown to the method caller to proceed with the next step.
(4) The exception is caught and handled in the caller who has the exception method.

custom exceptions See the code example above to throw an exception using throw.

The exception is reflected in the child parent class:
(1), subclasses when overriding the parent class, if the parent class throws a method exception, then the subclass's override method can only throw the parent class's exception or subclass of the exception
(2) If multiple exceptions are thrown in the parent class method, the subclass can only throw a subset of the parent class exception when overriding the method.
(3) If there is no exception thrown in the method of the parent class or interface, then the subclass cannot throw an exception when it overrides the method. If an exception is made to a subclass method, you must do a try processing and never throw it.

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.