Java Exception Framework Design

Source: Internet
Author: User
Tags getmessage stack trace throw exception throwable

What is an exception?

The exception (exception) should be an abbreviation for the exception event (exceptional event).
Exception definition: An exception is an event that occurs during the execution of a program that interrupts the normal instruction flow of the program being executed.
When an error occurs in a method, this method creates an object and passes it to the runtime system. This object is called an exception object, and it contains information about the error, including the type of the error and the state of the error when the program occurred. Creating an Error object and passing it to the runtime system is called throwing an exception.
Once a method throws an exception, the runtime will try to find some way to handle it. The collection of these possible methods of handling exceptions is a list of methods that are sorted together, and these methods can be called by the wrong method. This list of methods is called a stack call (calling stack)

The runtime system searches for the stack that contains the method requested by the code block that handles the exception. This block of code is called the exception handler, and the search begins with the method that occurred, then retrieves the call stack in reverse order of the calling method. When a corresponding processor is found, the runtime system passes the exception to the processor. An exception handler is required to properly filter the type of exception object that is thrown and whether the type of exception handled by the exception handler matches. After the exception is captured, the exception handler shuts down. If the runtime system searches all of the call stacks for this method, it does not find the appropriate exception handler.



How to design an anomaly frame

Any exception is a Throwable class (why not an interface??). ), and under it contains two Word class error/exception, and the error only throws an error object when a dynamic connection failure occurs in a Java virtual machine or if another location fails. Typical simple programs do not capture or throw errors objects, you may never encounter an application that needs to instantiate an error, so let's take a look at exception

The important thing in exception is that the runtimeexception-runtime exception (of course the name is controversial, because any exception will only occur at runtime), why is it important to say this class? Because it's directly related to the design of your anomaly frame, look closely at RuntimeException

A method is not required to declare in it throws clause any subclasses of runtimeexception the might be thrown during th E execution of the method but not caught.

-Any subclass of RuntimeException that may have been thrown but not captured during the execution of the method does not need to be declared in the throws clause.

That is, your application should not "care" (said not to care is not responsible, but you should not try to instantiate its word class) RuntimeException, just as you should not care about the error of the production and processing! RuntimeException describes the error of the program caused by the program to bear this responsibility! (<B> from the perspective of responsibility, error is the responsibility of the JVM to bear; RuntimeException is the responsibility that the procedure should bear; Checked exception is the responsibility of the concrete application burden </B>)

Then someone will ask, what should I care about! The answer is that except for error and RuntimeException, the rest of the exception is what you need to care about, and these exception classes collectively referred to as checked Exception, as for the error and RuntimeException is collectively referred to as unchecked Exception.


This is the concept of the anomaly, even if you search on the Internet is no more than that, do you feel a bit clear and a little blurred? So how to design the abnormal framework of the Java EE in such a thin and vague concept?


Solution: Java EE exception framework

Let's take a simulation example to illustrate the design of the anomaly framework, for example, we want to provide dobusiness () this business method

public void Dobusiness () throws Xxxbusinessexception

This should be handled when the client calls such a method (including handling runtimeexception, checked exception)
<B> Remember, anyway, we don't want or exactly say that runtimeexception should not be exposed to customers because they don't have the responsibility to solve the problem! </B>
We temporarily treat an action in struts as a client, where Doexecute (...) To call Dobusiness () this method

public void doAction (...)
{
Try
{

Xxx.dobusiness ();
}
catch (Exception e)
{
if (e instanceof runtimeexception)
{
Catch Runtime exception
You can capture the runtimeexception here
Notifies an exception to a programmer who is responsible for this program and lets him know that he
What a low-level mistake you have made!


}else
{
Checked exception such as Xxxbusinessexception
Exposing such anomalies to the customer display

}

}
}

We can design xxxbusinessexception like this.

public class Xxxbusinessexception extends ApplicationException
{
Public Xxxbusinessexception (String s) {
Super (s);

};

Import Java.io.PrintStream;
Import Java.io.PrintWriter;
public class ApplicationException extends Exception {
/** A wrapped Throwable */
protected throwable cause;
Public ApplicationException () {
Super ("Error occurred in Application.");
}
Public applicationexception (String message) {
Super (message);
}
Public ApplicationException (String message, throwable cause) {
Super (message);
This.cause = cause;
}
Created to match the JDK 1.4 Throwable method.
Public Throwable initcause (Throwable cause) {
This.cause = cause;
return cause;
}
Public String GetMessage () {
Get This exception ' s message.
String msg = Super.getmessage ();
Throwable parent = this;
Throwable child;
Look for nested exceptions.
while ((Child = getnestedexception (parent)) = null) {
Get the child ' s message.
String MSG2 = Child.getmessage ();
If we found a message for the child exception,
We append it.
if (MSG2! = null) {
if (msg! = null) {
msg + = ":" + msg2;
} else {
msg = MSG2;
}
}
Any nested applicationexception would append its own
Children, so we need-break out of here.
if (child instanceof ApplicationException) {
Break
}
parent = child;
}
Return the completed message.
return msg;
}
public void Printstacktrace () {
Print the stack trace for this exception.
Super.printstacktrace ();
Throwable parent = this;
Throwable child;
Print the stack trace for each nested exception.
while ((Child = getnestedexception (parent)) = null) {
if (child! = null) {
System.err.print ("caused by:");
Child.printstacktrace ();
if (child instanceof ApplicationException) {
Break
}
parent = child;
}
}
}
public void Printstacktrace (PrintStream s) {
Print the stack trace for this exception.
Super.printstacktrace (s);
Throwable parent = this;
Throwable child;
Print the stack trace for each nested exception.
while ((Child = getnestedexception (parent)) = null) {
if (child! = null) {
S.print ("caused by:");
Child.printstacktrace (s);
if (child instanceof ApplicationException) {
Break
}
parent = child;
}
}
}
public void Printstacktrace (PrintWriter w) {
Print the stack trace for this exception.
Super.printstacktrace (w);
Throwable parent = this;
Throwable child;
Print the stack trace for each nested exception.
while ((Child = getnestedexception (parent)) = null) {
if (child! = null) {
W.print ("caused by:");
Child.printstacktrace (w);
if (child instanceof ApplicationException) {
Break
}
parent = child;
}
}
}
Public Throwable Getcause () {
return cause;
}
}

and the "smart" reader must ask me the dobusiness () How does this business method package the exception?

public void dobusiness () throw xxxbusinessexception
{
Try
{
Execute1 (); If it throw Exception1

Exexute2 (); If it throw exception 2

.... .....

}
catch (Exception1 E1)
{
throw new Xxxbusinessexception (E1);
}
catch (exception2 E2)
{
throw new Xxxbusinessexception (E2);
}
........
}

You can do that.

public void dobusiness () throw xxxbusinessexception
{
Try
{
Execute1 (); If it throw Exception1

Exexute2 (); If it throw exception 2

.... .....

}
catch (Exception e)
{
Note that many applications here do not judge the type of anomaly and the use of a brain
throw new Xxxbusinessexception (e);
And the problem is that xxxbusinessexception "swallowed" runtimeexception
So the checked excption and unchecked exception mixed together!

In fact, xxxbusinessexception belongs to checked excpetion, it should not be able to ignore RuntimeException
if (! e instanceof runtimeexception) throw new Xxxbusinessexception (e);
}
}


Summarize
1. Java exceptions fall into two categories: Checked exception & Unchecked excpetion
2. Exceptions generated in application development should be integrated from exception but are checked excpetion types
3. Each layer in the application filters out the runtimeexception! when it wraps and passes the exception
4. From the point of view of responsibility, error belongs to the burden of the JVM. RuntimeException is the responsibility that the procedure should bear; Checked exception is the responsibility of the concrete application burden

5. In any case, we do not want or specifically should not be runtimeexception such an exception to the customer, because they do not solve the problem of responsibility!

Related articles:

http://blog.csdn.net/luqin1988/article/details/7970792

Java Exception Framework Design

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.