- The
tryblock will execute a sensitive code which can throw exceptions - The
catchblock will be used whenever an exception (of the type caught) is thrown in the try block - The
finallyblock is called in every case after the try/catch blocks. Even if the exception isn't caught or if your previous blocks break the execution flow. - The
throwkeyword will allow you to throw an exception (which will break the execution flow and can be caught in acatchblock). - The
throwskeyword in the method prototype is used to specify that your method might throw exceptions of the specified type. It's useful when you have checked exception (exception that you have to handle) that you don't want to catch in your current method.
Resources :
- oracle.com - Lesson: Exceptions
On another note, you should really accept some answers. If anyone encounter the same problems as you and find your questions, he/she will be happy to directly see the right answer to the question.
Answer from Colin Hebert on Stack Overflow- The
tryblock will execute a sensitive code which can throw exceptions - The
catchblock will be used whenever an exception (of the type caught) is thrown in the try block - The
finallyblock is called in every case after the try/catch blocks. Even if the exception isn't caught or if your previous blocks break the execution flow. - The
throwkeyword will allow you to throw an exception (which will break the execution flow and can be caught in acatchblock). - The
throwskeyword in the method prototype is used to specify that your method might throw exceptions of the specified type. It's useful when you have checked exception (exception that you have to handle) that you don't want to catch in your current method.
Resources :
- oracle.com - Lesson: Exceptions
On another note, you should really accept some answers. If anyone encounter the same problems as you and find your questions, he/she will be happy to directly see the right answer to the question.
If you execute the following example, you will know the difference between a Throw and a Catch block.
In general terms:
The catch block will handle the Exception
throws will pass the error to his caller.
In the following example, the error occurs in the throwsMethod() but it is handled in the catchMethod().
public class CatchThrow {
private static void throwsMethod() throws NumberFormatException {
String intNumber = "5A";
Integer.parseInt(intNumber);
}
private static void catchMethod() {
try {
throwsMethod();
} catch (NumberFormatException e) {
System.out.println("Convertion Error");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
catchMethod();
}
}
Yes, there's a huge difference - the latter swallows the exception (showing it, admittedly), whereas the first one will let it propagate. (I'm assuming that showException doesn't rethrow it.)
So if you call the first method and "do something" fails, then the caller will have to handle the exception. If you call the second method and "do something" fails, then the caller won't see an exception at all... which is generally a bad thing, unless showException has genuinely handled the exception, fixed whatever was wrong, and generally made sure that calculateArea has achieved its purpose.
You'll be able to tell this, because you can't call the first method without either catching Exception yourself or declaring that your method might throw it too.
They differ in where the responsibility to deal with the Exception lies. First one just throws Exception, so it does not handle it. The code that calls the method needs to handle the Exception. Second one catches and handles the Exception within the method, so in this case the caller doesn't have to do any exception handling, provided showException() itself does not throw another exception.
Videos
- catch an exception only if you can handle it in a meaningful way
- declare throwing the exception upward if it is to be handled by the consumer of the current method
- throw exceptions if they are caused by the input parameters (but these are more often unchecked)
In general, a method should throw an exception to its caller when it can't handle the associated problem locally. E.g. if the method is supposed to read from a file with the given path, IOExceptions can't be handled locally in a sensible way. Same applies for invalid input, adding that my personal choice would be to throw an unchecked exception like IllegalArgumentException in this case.
And it should catch an exception from a called method it if:
- it is something that can be handled locally (e.g. trying to convert an input string to a number, and if the conversion fails, it is entirely valid to return a default value instead),
- or it should not be thrown (e.g. if the exception is coming from an implementation-specific lower layer, whose implementation details should not be visible to the caller โ for example I don't want to show that my
DAOusesHibernatefor persisting my entities, so I catch allHibernateExceptionslocally and convert them into my own exception types).
Pretty new student to CS here. I'm curious what the point of throwing an exception is. Does it actually do anything?
Wouldn't the try/catch always be better as you catch for errors and actually deal with them in some way?
Why not to try in code?
public class ExPerformanceTest {
private int someVar = 0;
private int iterations = 100000000;
@Test
public void throwTest() throws Exception {
long t;
t = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
throwingMethod();
}
t = System.currentTimeMillis() - t;
System.out.println("Throw Test took " + t + " ms");
}
@Test
public void tryCatchTest() throws Exception {
long t;
t = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
tryCatchMethod();
}
t = System.currentTimeMillis() - t;
System.out.println("Try-Catch Test took " + t + " ms");
}
@Test
public void anotherTryCatchTest() throws Exception {
long t;
t = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
tryCatchMethodThatNeverEverThrows();
}
t = System.currentTimeMillis() - t;
System.out.println("Try-Catch That Never Throws Test took " + t + " ms");
}
private void throwingMethod() throws Exception {
// do some stuff here
someVar++;
willNeverThrow();
}
private void tryCatchMethod() {
try {
// do some stuff here
someVar++;
willNeverThrow();
} catch (Exception e) {
System.out.println("You shouldn't see this ever");
}
}
private void tryCatchMethodThatNeverEverThrows() {
try {
// do some stuff here
someVar++;
} catch (Exception e) {
System.out.println("You shouldn't see this ever");
}
}
private void willNeverThrow() throws Exception {
if (someVar == -1) {
throw new RuntimeException("Shouldn't happen");
}
}
}
That gives quite expected numbers:
Run 1
Try-Catch That Never Throws Test took 36 ms
Throw Test took 139 ms
Try-Catch Test took 160 ms
Run 2
Try-Catch That Never Throws Test took 26 ms
Throw Test took 109 ms
Try-Catch Test took 113 ms
Run 3
Try-Catch That Never Throws Test took 32 ms
Throw Test took 137 ms
Try-Catch Test took 194 ms
Obviously, JVM spotted that tryCatchMethodThatNeverEverThrows doesn't effectively need a catch part and optimized that, so the method execution took few times less, than others.
In other case, having a catch clause with handling takes some time indeed.
From the paper, Optimizing Java Programs in the Presence of Exceptions:
The Java language specification requires that exceptions be precise, which implies that:
- when an exception is thrown, the program state observable at the entry of the corresponding exception handler must be the same as in the original program; and
- exception(s) must be thrown in the same order as specified by the original (unoptimized) program.
To satisfy the precise exception requirement, Java compilers disable many important optimizations across instructions that may throw an exception...This hampers a wide range of program optimizations such as instruction scheduling, instruction selection, loop transformations, and parallelization.
In presence of a try-catch block, JVM maintains an exception table. For each new catch block, the compiler will add an entry to the exception table. If an exception occurs, JVM needs to go through each entry in the table and check if the exception is defined in the exception table (this requires type analysis too). The result is a much more complex control structure which in turn will greatly hamper compiler optimization.
throws on the other hand, allows the exception to propagate. Although this might be better for performance, an uncaught exception can potentially crash the thread, the whole application, or even kill the JVM itself!
How to decide when to use try-catch?
I think correctness and reliability concerns play a more important role than performance here. But if you have only performance in mind, the authors in this link have done extensive bench-marking for java code in presence of exceptions. Their most basic conclusion is that if you use exceptions for truly exceptional cases (not as a means for program flow control) there will not be much of a performance hit.