By exception handling errors (2): Create a custom exception, exception description

 First, create a custom exception

    You do not have to rigidly adhere to the existing exception type in java. Abnormal system supplied java impossible to foresee all hope to be reporting errors, so you can custom exception class to represent a particular problem in the program may encounter.

    To define your own exception classes must inherit from the existing exception classes, the best choice is the exception class inherits similar meaning (but this exception is not easy to find). Create a new exception type is the easiest way to let the compiler generates a default constructor for you, so it is almost without writing much code:

class SimpleException extends Exception {
}

public class InheritingExceptions {
	public void f() throws SimpleException {
		System.out.println("Throw SimpleException from f()");
		throw new SimpleException();
	}

	public static void main(String[] args) {
		InheritingExceptions sed = new InheritingExceptions();
		try {
			sed.f();
		} catch (SimpleException e) {
			System.out.println("捕捉异常");
		}
	}
}

    The compiler creates a default constructor, it will automatically call the default constructor of the base class. The present embodiment will not be as SimpleException (String) This constructor, this configuration is not practical. You will see the abnormal, the most important part is the class name, so in this case an exception class created in most cases it has been good enough.

    The results of this example are printed to the console, however, and you might want to be sent to the standard error stream by writing to System.err error. Usually this System.out output better error messages than to, because System.out might be redirected. If the result to System.err, it will not be redirected along with System.out, so that the user's attention more easily.

    A constructor may be acceptable for the string parameter exception classes:

class MyException extends Exception {
	public MyException() {
	}

	public MyException(String msg) {
		super(msg);
	}
}

public class FullConstructors {
	public static void f() throws MyException {
		System.out.println("Throwing MyException from f()");
		throw new MyException();
	}

	public static void g() throws MyException {
		System.out.println("Throwing MyException from g()");
		throw new MyException("Originated in g()");
	}

	public static void main(String[] args) {
		try {
			f();
		} catch (MyException e) {
			e.printStackTrace(System.out);
		}
		try {
			g();
		} catch (MyException e) {
			e.printStackTrace(System.out);
		}
	}
}

    The new code is not long: two constructors to create a defined way MyException type of object. For the second configuration, a super keyword using an explicit call to the base class constructor, which accepts a string argument.

    In an exception handler, called the class declaration in printStackTrace Throwable (Exception that is inherited from this class) of () method. As seen from the output, it will print method "exception is thrown up at the call of the method," the calling sequence. Here, the information is transmitted to the System.out, and automatically captured and displayed in the output. However, if you call the default version: e.printStackTrace (); the message is output to the standard error stream.

Second, abnormal and logging

    You may also want to use java.util.logging tool output logged. As used herein, basic logging function is fairly straightforward:

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.Logger;

class LoggingException extends Exception {
	private static Logger logger = Logger.getLogger("LoggingException");

	public LoggingException() {
		StringWriter trace = new StringWriter();
		printStackTrace(new PrintWriter(trace));
		logger.severe(trace.toString());
	}
}

public class LoggingExceptions {
	public static void main(String[] args) {
		try {
			throw new LoggingException();
		} catch (LoggingException e) {
			System.err.println("捕捉:" + e);
		}
		try {
			throw new LoggingException();
		} catch (LoggingException e) {
			System.err.println("捕捉:" + e);
		}
	}
}

    Static Logger.getLogger () method creates a Logger object parameter associated with the String (usually the package name and class name associated with the error), this Logger object will send its output to System.err. The easiest way is to write Logger directly call the method level messages associated with logging, used here is servere (). In order to generate logging messages we want to get the stack trace exception is thrown at, but printStackTrace () does not produce the string by default. In order to get the string, we need to use overloaded printStackTrace () method, which takes a java.io.PrintWriter object as a parameter. If we java.io.StringWriter a PrintWriter object to the constructor, then by calling the toString () method, you can export extracted as a String.

    Although the LoggingException the infrastructure of all logging are built itself an exception in such a way that it is very easy to use, and therefore does not require the client programmer intervention can be run automatically, but a more common scenario is that we need to capture and abnormal records written by others, so we must generate log messages in an exception handler:

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.Logger;

public class LoggingException2 {
	private static Logger logger = Logger.getLogger("LoggingException2");

	static void logException(Exception e) {
		StringWriter trace = new StringWriter();
		e.printStackTrace(new PrintWriter(trace));
		logger.severe(trace.toString());
	}

	public static void main(String[] args) {
		try {
			throw new NullPointerException();
		} catch (Exception e) {
			logException(e);
		}
	}
}

    You can also further customize exceptions, such as adding extra constructors and members:

class MyException2 extends Exception {
	private int x;

	public MyException2() {
	}

	public MyException2(String msg) {
		super(msg);
	}

	public MyException2(String msg, int x) {
		super(msg);
		this.x = x;
	}

	public int val() {
		return x;
	}

	public String getMessage() {
		return "Detail Message: " + x + " " + super.getMessage();
	}
}

public class ExtraFeatures {
	public static void f() throws MyException2 {
		System.out.println("Throwing MyException2 from f()");
		throw new MyException2();
	}

	public static void g() throws MyException2 {
		System.out.println("Throwing MyException2 from g()");
		throw new MyException2("Originated in g()");
	}

	public static void h() throws MyException2 {
		System.out.println("Throwing MyException2 from h()");
		throw new MyException2("Originated in h()", 47);
	}

	public static void main(String[] args) {
		try {
			f();
		} catch (MyException2 e) {
			e.printStackTrace(System.out);
		}
		try {
			g();
		} catch (MyException2 e) {
			e.printStackTrace(System.out);
		}
		try {
			h();
		} catch (MyException2 e) {
			e.printStackTrace(System.out);
			System.out.println("e.val() = " + e.val());
		}
	}
}

    Adding a new exception constructors x field and a setting value of x and the method of reading data. In addition, also covers the Throwable.getMessage () method to generate more detailed information. For the exception class is, getMessage () method is somewhat similar to toString () method.

    Since it is an unusual object, so we can continue to modify the exception class, in order to obtain greater functionality. But remember, use package client programmer might just look at the type of exception thrown, the other on the matter (most java library exceptions are so used), so abnormal added other features probably did not have access.

Third, the exception description

    encourage people to java method may throw exceptions inform the client programmer using this method. This is the kind of elegant approach, which allows the caller can know exactly what code to write can capture the potential exception. Of course, if the source code is the client programmer can look for throw statements in the source code to obtain relevant information, but libraries are not usually distributed with source code. To prevent such problems, java provides the appropriate syntax (grammar and enforce the use of this), so you can tell the client programmer exception types that a method might throw in a polite way, and then the client programmer can performs corresponding processing. This is the exception specification, which is part of the method declaration, followed later in the form of a list of parameters.

    Exception description using additional keywords throws, followed by an all potential exception type list, so the method definition might look like this:

void f() throws TooBig, TooSmall, DivZero{ /* ... */}

    But if this void f () {/ * ... * /}, it means that this method does not throw any exception (inherited from a RuntimeException, they may be thrown in the case where there is no abnormality description, which will discussed later).

    Code must be consistent with the exception description. If the method in the code that creates an exception has not been processed, the compiler will find this issue and remind you: either handle the exception, or to show that this method generates an exception in the exception description. In this top-down force mechanism described abnormality executed, java at compile time can guarantee a certain level of accuracy of abnormality.

    However, there are a can "cheat" place: You can declare method will throw an exception, in fact, not thrown. The compiler believe this statement, and force users to really like this method throws an exception that use this method. The advantage of this is that abnormal pre-emption seats, since you can throw this exception without modifying existing code. This capability is important when defining the abstract base classes and interfaces, so that the derived class or interface can throw an exception these pre-declared.

    This is forced at compile time checking of abnormalities known as the exception is checked.

 

If this article is very helpful to you, please also like to look at.

Published 100 original articles · won praise 2 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_40298351/article/details/104456031
Recommended