Java-based exceptions

Source: Internet
Author: User
Tags try catch

 
 

The simple principle and application of the exception handling mechanism in Java:

Exceptions are exceptions or errors that occur when Java programs are running (not compiled). They are similar to events in real life, events in real life can contain information such as the time, location, character, and plot of an event. They can be represented by an object. Java uses an object-oriented method to handle exceptions, it encapsulates every exception in the program into an object, which contains the exception information.

Java classifies exceptions. Different types of exceptions are represented by different Java classes. The root classes of all exceptions are Java. lang. throwable and throwable have two subclasses: Error and exception. Error indicates a serious problem that the application itself cannot overcome and restore. The program has only dead parts. For example, system problems such as memory overflow and thread deadlock. Exception indicates that the program can also overcome and recover the problems, including system exceptions and Common exceptions. system exceptions are caused by Software defects, that is to say, software developers cannot overcome and restore the problems caused by weeks of consideration. However, in this case, the software system can continue to run or let the software die. For example, array script out of bounds (arrayindexoutofboundsexception), null pointer exception (nullpointerexception), Class conversion exception (classcastexception); normal exceptions are caused by changes in the runtime environment or exceptions, it is a problem that users can overcome, such as network disconnection and insufficient hard disk space. After such an exception occurs, the program should not die.

Java provides different solutions for system exceptions and Common exceptions. The Compiler forces normal exceptions to try .. catch processing or throws declaration is used to continue to be thrown to the upper-layer call method for processing. Therefore, common exceptions are also called checked exceptions, and system exceptions can be handled or not processed. Therefore, the compiler does not force try .. catch or throws are used for processing. Therefore, a system exception is also called an unchecked exception.

 

First, let's take a look at the abnormal system:

Throwable:
Error: there are usually major problems, such as the nonexistent running class or memory overflow.
Do not write code to process it

Exception: a condition that occurs when running. You can use try {} catch () {} finally {}

Both the exception and error sub-classes use the parent class name as the suffix.

Such as runtimeexception

Some common methods in trowable:

Getmessage () gets exception information and returns a string.

Tostring () to obtain the exception class and exception information

Printstacktrace () gets the exception class name and exception information, and the location where the exception occurs in the program. Return Value void

Printstacktrace (printstream S)

This method is usually used to save the exception content in the log file for reference.

 

Exception Handling Format:

Try
{
Code to be detected;
}
Catch (exception variables)
{
Exception Handling Code;
}
Finally
{
Code that will be executed;
}

Note: The finally code block is not executed in only one case. System. Exit (0) is executed before ).

Other code in the Method

If the code is correct, the program runs down without a catch statement;

If the code is incorrect, the returned exception object matches E. If the matching is successful, the Exception Processing code following it is processed.

If an error is found in try, that is, the try block exists to match catch, then the statement after try will not be executed.

A try can be used with multiple catch statements to handle different situations, but the location of the parent exception cannot be written before the child-type commit iton.

After try-catch, you can use the finally clause. Any exception in the Code statement theory will be executed (because of this feature of the finally clause, the statement for releasing resources and closing connections is usually written in it ).

When the code in finally conflicts with the code in try-catch, the code in finally will be executed and the code in try-catch will be ignored. However, if system. Exit (0); (Virtual Machine exit statement) exists in try-catch, the code in fianlly is not executed.

Throws/throw processing method:

Throw is written in the method, followed by an exception object.

Throws describes the exceptions that a method may throw in the definition of the method, followed by the name of the exception class. It declares that this method will not handle the exception and submits the exception to the upper-level method for processing.

During the call, the caller cannot throw an exception with a smaller range.

For method A, if it defines throws exception. When Method B is called to return an exception object, method A does not process it, but returns the exception object to the upper-level. If no methods are processed, the system returns the object to the primary method, if the master method is not processed, the program is aborted on the VM.

If there is a row of throw new exception () in the method program, the subsequent program will not be executed. If the possible check result is not processed, the program will report an error.

Throws and throw are not necessarily related.

Note:

If the exception thrown by the subclass method is the parent type thrown by the parent class method, the compilation will fail: The subclass cannot overwrite the parent class.

The exception thrown by the subclass is the same as that thrown by the parent class, the child type thrown by the parent class, or the child type does not throw the exception.

If the parent type does not have throws, throws cannot appear for the child type. You can only use try catch.

Custom exception:

A. inherit exception or runtimeexception.

B. The write constructor directly calls the constructor of the parent class.

Assert: Used to debug and test code

 

Difference between throw and throw keywords:

Throws is used in functions. It is followed by the exception class name. You can append multiple exception class names separated by commas (,).

Throw is used in the function, followed by an exception object.

 

Formats of exception handling:

First format:
Try
{
 
}
Catch ()
{
}

Second format:
Try
{
 
}
Catch ()
{
}
Finally
{

}

Third format:
Try
{
 
}
Finally
{
}
Note: Catch is used to handle exceptions. If no catch is found, the exception has not been processed. If the exception is detected. It must be declared.

 

Custom exception:

// Custom exception, used to handle the case where the divisor is negative:

*/
Class fushuexception extends exception // getmessage ();
{
Private int value;

Fushuexception ()
{
Super ();
}
Fushuexception (string MSG, int value)
{
Super (MSG );
This. value = value;
}

Public int getvalue ()
{
Return value;
}

}

 

Class demo
{
Int Div (int A, int B) throws fushuexception
{
If (B <0)
Throw new fushuexception ("when the divisor is negative ------/by fushu", B); // manually throw a custom exception object through the throw keyword.

Return A/B;
}
}

Class exceptiondemo3
{
Public static void main (string [] ARGs)
{
Demo d = new demo ();
Try
{
Int x = D. Div (4,-9 );
System. Out. println ("x =" + x );
}
Catch (fushuexception E)
{
System. Out. println (E. tostring ());
// System. Out. println ("the divisor has a negative number ");
System. Out. println ("the negative number of the error is:" + E. getvalue ());
}

System. Out. println ("over ");

}
}

/*
Class throwable
{
Private string message;
Throwable (string message)
{
This. Message = message;
}

Public String getmessage ()
{
Return message;
}
}

 

 

Notes for usage exceptions:

1. If runtimeexception and its subclass are throttled by throw in the function, you do not need to declare it on the function.

For example, arithmeticexception can be avoided through code processing.

2. If a custom exception occurs, you cannot continue to calculate the exception. You can inherit runtimexception from the custom exception.

3. If the parent class throws multiple exceptions, the override (overwrite) method must throw a subset of those exceptions and cannot throw new exceptions.

 

Summary of access between packages:

Access between packages. The classes in the accessed package and the Members in the class must be public.

Child classes in different packages can also directly access members modified by the protected permission in the parent class.

There are only two types of permissions available between a package and a package: Public protected.

Public protected default private
In the same class, OK
In the same package, OK
Subclass OK
OK in different packages

 

Java. LANG: After JDK is the core package of Java, classes in this package are automatically imported.
Java. AWT: used to create a graphical interface.
Java. IO: input output is used to operate data on devices.
Java. util: it is defined as a Java tool class. Set, date.
Java.net: used for network communication.

 

 

 

 

 

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.