The Java exception hierarchy can't foresee all the errors we might report, so we can create our own to denote a special problem that your library might encounter.
// exceptions/FullConstructors.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
class MyException extends Exception {
MyException() {}
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); // public void printStackTrace(PrintStream s)
}
try {
g();
} catch (MyException e) {
e.printStackTrace(System.out);
// to the standard error stream.
e.printStackTrace();
}
}
}
/* My Output:
Throwing MyException from f()
MyException
at FullConstructors.f(FullConstructors.java:17)
at FullConstructors.main(FullConstructors.java:27)
Throwing MyException from g()
MyException: Originated in g()
at FullConstructors.g(FullConstructors.java:22)
at FullConstructors.main(FullConstructors.java:32)
MyException: Originated in g()
at FullConstructors.g(FullConstructors.java:22)
at FullConstructors.main(FullConstructors.java:32)
*/
A PrintStream
adds functionality to another output stream, namely the ability to print representations of various data values conveniently. Two other features are provided as well. Unlike other output streams, a PrintStream
never throws an IOException
; instead, exceptional situations merely set an internal flag that can be tested via the checkError
method. Optionally, a PrintStream
can be created so as to flush automatically; this means that the flush
method is automatically invoked after a byte array is written, one of the println
methods is invoked, or a newline character or byte ('\n'
) is written.
All characters printed by a PrintStream
are converted into bytes using the platform's default character encoding. The
class should be used in situations that require writing characters rather than byte.PrintWriter
references:
1. On Java 8 - Bruce Eckel
2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/exceptions/FullConstructors.java
4. https://docs.oracle.com/javase/8/docs/api/java/io/PrintStream.html
5. http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/System.java