Slide navigation: Forward with space bar, → arrow key, or PgDn. Backwards with ← or PgUp.


Exception but not of RuntimeException.throws clause:
public Image loadImage(String s) throws IOException
throws clause can list multiple exceptions:
public Image loadImage(String s) throws FileNotFoundException, EOFException
void drawImage(int i) throws ArrayIndexOutOfBoundsException // bad styleInstead, fix your code so that this doesn't happen!
Content-length: 1024, but you got an end of file after 733 characters.EOFException with description: “Signals that an EOF has been reached unexpectedly during input.”throw new EOFException();
String gripe = "Content-length: " + len + ", Received: " + n; throw new EOFException(gripe);
Exception, RuntimeException, or preferably a more specific exception class:
class FileFormatException extends IOException
{
public FileFormatException() {}
public FileFormatException(String gripe) { super(gripe); }
}if (n < len) throw new FileFormatException();
try/catch block to catch an exception:
try
{
code
more code
more code
}
catch (ExceptionType e)
{
handler for this type
}catch clauses:
try
{
code that might throw exceptions
}
catch (FileNotFoundException | UnknownHostException e)
{
emergency action for missing files and unknown hosts
}
catch (IOException e)
{
emergency action for all other I/O problems
}try
{
access the database
}
catch (SQLException e)
{
throw new ServletException("database error: " + e.getMessage());
}...
catch (SQLException e)
{
Throwable se = new ServletException("database error");
se.initCause(e);
throw se;
}getCause method.finally ClausePrintWriter out = new PrintWriter(...); . . . out.close();
. . . code throws an exception?out.close() statement is never executed!finally clause:
PrintWriter out = new PrintWriter(...);
try
{
. . .
}
finally
{
out.close();
}
try (Resource res = . . .)
{
work with res
}AutoCloseable interface, which has a single method:
void close() throws Exception
try (Scanner in = new Scanner(Paths.get("in.txt"), "UTF-8");
PrintWriter out = new PrintWriter("out.txt"))
{
while (in.hasNext())
out.println(in.next().toUpperCase());
}
try block throws an exception, and so does one of the close methods?catch (Exception e) { e.printStackTrace(); }
StringWriter out = new StringWriter(); e.printStackTrace(new PrintWriter(out)); String description = out.toString();
StackTraceElement[] frames = e.getStackTrace(); for (StackTraceElement frame : frames) ...
Thread.setDefaultUncaughtExceptionHandler((Thread t, Throwable e) -> ...);
try Blocks
try-with-resources can be used with an effectively final variable:
void print(PrintWriter out, String[] lines) {
try (out) { // Effectively final variable
for (String line : lines)
out.println(line.toLowerCase());
}
}out was not declared in the try block.try
{
s.pop();
}
catch (EmptyStackException e)
{
} |
⇒ | if (!s.empty()) s.pop(); |
for (i = 0; i < 100; i++)
{
try { n = s.pop(); }
catch (EmptyStackException e) { . . . }
try { out.writeInt(n); }
catch (IOException e) { . . . }
}
|
⇒ | try
{
for (i = 0; i < 100; i++)
{
n = s.pop();
out.writeInt(n);
}
}
catch (IOException e) { . . . }
catch (EmptyStackException e) { . . . }
|
RuntimeException. Find an appropriate subclass or create
your own.Throwable.try
{
code that threatens to throw checked exceptions
}
catch (Exception e)
{} // so theredouble y = Math.sqrt(x);You are certain that
x is not negative.if (x < 0) throw new IllegalArgumentException("x < 0");assert x >= 0;When assertions are enabled, an
AssertionError is thrown.assert x >= 0 : x;
java -enableassertions MyApp
java -ea:MyClass -ea:com.horstmann.corejava -da:AnotherClass MyApp
a must not be null.assert a != null;a is null, the program is aborted with a clear error...if (i % 3 == 0) . . .
else if (i % 3 == 1) . . .
else
{
assert i % 3 == 2;
. . .
}assert i >= 0;
System.out.println calls.info method:
Logger.getGlobal().info("File->Open menu item selected");May 10, 2013 10:12:15 PM LoggingImageViewer fileOpen INFO: File->Open menu item selected
Logger.getGlobal().setLevel(Level.OFF);
private static final Logger myLogger = Logger.getLogger("com.mycompany.myapp");com.mycompany.myapp inherits log settings on the com.mycompany logger.SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINESTlogger.setLevel(Level.FINE);
logger.warning(message); logger.fine(message); logger.log(Level.FINE, message);
INFO, you need to change the log handler configuration.int read(String file, String pattern)
{
logger.entering("com.mycompany.mylib.Reader", "read",
new Object[] { file, pattern });
. . .
logger.exiting("com.mycompany.mylib.Reader", "read", count);
return count;
}IOException exception = new IOException(". . .");
logger.throwing("com.mycompany.mylib.Reader", "read", exception);
throw exception;
...
catch (IOException e)
{
logger.log(Level.WARNING, "Reading image", e);
}
/lib/logging.propertiesjava -Djava.util.logging.config.file=configFile MyProg
.level=INFO
com.mycompany.myapp.level=FINE
jconsole tool.ConsoleHander instance.
System.errjava.util.logging.ConsoleHandler.level=INFO
logger.setUseParentHandlers(false) to turn off.FileHandler handler = new FileHandler(); logger.addHandler(handler);
javan.log in home directory.java.util.logging.FileHandler.pattern=%h/myapp%u.log