Java runtime exception handler

Putting It All Together

The previous sections described how to construct the try , catch , and finally code blocks for the writeList method in the ListOfNumbers class. Now, let’s walk through the code and investigate what can happen.

When all the components are put together, the writeList method looks like the following.

public void writeList() < PrintWriter out = null; try < System.out.println("Entering" + " try statement"); out = new PrintWriter(new FileWriter("OutFile.txt")); for (int i = 0; i < SIZE; i++) < out.println("Value at: " + i + " = " + list.get(i)); >> catch (IndexOutOfBoundsException e) < System.err.println("Caught IndexOutOfBoundsException: " + e.getMessage()); >catch (IOException e) < System.err.println("Caught IOException: " + e.getMessage()); >finally < if (out != null) < System.out.println("Closing PrintWriter"); out.close(); >else < System.out.println("PrintWriter not open"); >> >

As mentioned previously, this method’s try block has three different exit possibilities; here are two of them.

  1. Code in the try statement fails and throws an exception. This could be an IOException caused by the new FileWriter statement or an IndexOutOfBoundsException caused by a wrong index value in the for loop.
  2. Everything succeeds and the try statement exits normally.

Let’s look at what happens in the writeList method during these two exit possibilities.

Scenario 1: An Exception Occurs

The statement that creates a FileWriter can fail for a number of reasons. For example, the constructor for the FileWriter throws an IOException if the program cannot create or write to the file indicated.

When FileWriter throws an IOException , the runtime system immediately stops executing the try block; method calls being executed are not completed. The runtime system then starts searching at the top of the method call stack for an appropriate exception handler. In this example, when the IOException occurs, the FileWriter constructor is at the top of the call stack. However, the FileWriter constructor doesn’t have an appropriate exception handler, so the runtime system checks the next method — the writeList method — in the method call stack. The writeList method has two exception handlers: one for IOException and one for IndexOutOfBoundsException .

Читайте также:  Java how to use lambda

The runtime system checks writeList ‘s handlers in the order in which they appear after the try statement. The argument to the first exception handler is IndexOutOfBoundsException . This does not match the type of exception thrown, so the runtime system checks the next exception handler — IOException . This matches the type of exception that was thrown, so the runtime system ends its search for an appropriate exception handler. Now that the runtime has found an appropriate handler, the code in that catch block is executed.

After the exception handler executes, the runtime system passes control to the finally block. Code in the finally block executes regardless of the exception caught above it. In this scenario, the FileWriter was never opened and doesn’t need to be closed. After the finally block finishes executing, the program continues with the first statement after the finally block.

Here’s the complete output from the ListOfNumbers program that appears when an IOException is thrown.

Entering try statement Caught IOException: OutFile.txt PrintWriter not open

The boldface code in the following listing shows the statements that get executed during this scenario:

public void writeList() < PrintWriter out = null; try < System.out.println("Entering try statement"); out = new PrintWriter(new FileWriter("OutFile.txt"));for (int i = 0; i < SIZE; i++) out.println("Value at: " + i + " = " + list.get(i)); >catch (IndexOutOfBoundsException e) < System.err.println("Caught IndexOutOfBoundsException: " + e.getMessage()); >catch (IOException e) < System.err.println("Caught IOException: " + e.getMessage()); >finally < if (out != null) System.out.println("Closing PrintWriter"); out.close(); > else > >

Scenario 2: The try Block Exits Normally

In this scenario, all the statements within the scope of the try block execute successfully and throw no exceptions. Execution falls off the end of the try block, and the runtime system passes control to the finally block. Because everything was successful, the PrintWriter is open when control reaches the finally block, which closes the PrintWriter . Again, after the finally block finishes executing, the program continues with the first statement after the finally block.

Here is the output from the ListOfNumbers program when no exceptions are thrown.

Entering try statement Closing PrintWriter

The boldface code in the following sample shows the statements that get executed during this scenario.

public void writeList() < PrintWriter out = null; try < System.out.println("Entering try statement"); out = new PrintWriter(new FileWriter("OutFile.txt")); for (int i = 0; i < SIZE; i++) out.println("Value at: " + i + " Caught IndexOutOfBoundsException: " + e.getMessage()); >catch (IOException e) < System.err.println("Caught IOException: " + e.getMessage()); >finally else < System.out.println("PrintWriter not open"); >> >

Previous page: The try-with-resources Statement
Next page: Specifying the Exceptions Thrown by a Method

Источник

Handling RuntimeExceptions in Java [closed]

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

I think the non-accepters of SO have figured out by now that those are empty threats. We want mod points!

It’s sad, but I have the impression that obvious 30-second answers to dumb questions usually give more reward points than well-written answers to more interesting questions. For questions with a high view rate, the first answer usually ends up with a lot of reward points even if it is not related to the question at all.

4 Answers 4

It doesn’t differ from handling a regular exception:

try < someMethodThatThrowsRuntimeException(); >catch (RuntimeException ex) < // do something with the runtime exception >

I dont see a problem with this question — I had a Runnable that I suspected was causing a runtime error and I wasn’t aware that you could just wrap any code in a try/catch & add a RunTimeException catch. I Googled’Android handling runtime exceptions’, this was the first question that came up & this answer provided what I needed. Surely thats exactly how SO should work?

If you know the type of Exception that might be thrown, you could catch it explicitly. You could also catch Exception , but this is generally considered to be very bad practice because you would then be treating Exceptions of all types the same way.

Generally the point of a RuntimeException is that you can’t handle it gracefully, and they are not expected to be thrown during normal execution of your program.

Except, perhaps, when a custom component is throwing a RuntimeException because it can not reach a certain host over network and that is crashing your Android app.

You just catch them, like any other exception.

try < somethingThrowingARuntimeException() >catch (RuntimeException re) < // Do something with it. At least log it. >

Not sure if you’re referring directly to RuntimeException in Java, so I’ll assume you’re talking about run-time exceptions.

The basic idea of exception handling in Java is that you encapsulate the code you expect might raise an exception in a special statement, like below.

Then, you handle the exception.

If you need certain things to execute regardless of whether an exception is raised, add finally .

All together it looks like this.

try < // Do something here >catch (AnotherException ex) < >catch (Exception e) < //Exception class should be at the end of catch hierarchy. >finally

Источник

Оцените статью