To handle an exce ption, you must set up a special block of code.
The way you set up a special block of code is by using the keywords try and catch.
The idea is that you try to execute a block of code that might throw an exception. You then indicate you will catch certain (or all) exceptions which might be thrown as a result of trying to execute that block.
Try to execute a method
invoke a method → Another Method
Method code
↓
Everything OK?
Yes → return normally → back to Your Code:
→ Continue on
No → throw an exception → back to Your Code:
→ Catch the exception
→ Continue on
This flowchart visually represents the **exception handling** mechanism in programming, such as `try-catch` in Java or similar constructs in other languages.
This is the basic code structure:
try{
/* execute code here that might cause an exception to be thrown */
}
catch(Exception e) {
/* handle any exceptions here that occurred in the try block */
}
Catching Exceptions
Catching exceptions is a bit like baseball. As you can see in the code snippet above, the catch keyword is followed by a parameter definition, just as if this were defining a method parameter. In the above example, this parameter definition is:
Catching Exceptions are like baseball
You might think of this as a game of baseball.
The pitcher (your code) will toss the ball (the thread of control) toward the batter (the method you are invoking in the try block).
As the pitcher, you want the ball to return to you in the normal way, and if it does, everything is fine.
However, if you hang a curve ball or something does not happen that you intended and the batter smashes the ball, the ball needs to be caught, because if it hits the ground, that thread of control will end. A person has to be prepared to catch the ball in case the batter hits it.
Exception Handling Variations
Exception handling syntax varies between programming languages in order to cover semantic differences.
The syntactic structure of programming languages requires that the try/catch block is expressed somewhat differently from one language to the next. Some languages do not call this concept exception handling, while others may not have direct facilities for it, but can still provide a means for implementing it.
Most commonly, error handling uses a
try...[catch...][finally...]
block, and errors are created by means of a throw statement.
When you call a method that throws an exception, there are two ways that you can treat the method call.
1. If the "main" method calls a method "doStuff()" that throws an Exception(as on line 1 below), the method call on line 3 can be handled using line 2.
Note: However, the exception will be not be caught and "Over" will not be printed.
public class TestClass {
public static void doStuff() throws Exception{ // line 1
System.out.println("Doing stuff...");
if(Math.random() > 0.4){
throw new Exception("Too high!");
}
System.out.println("Done stuff.");
}
public static void main(String[] args) throws Exception { // line 2
doStuff();// line 3
System.out.println("Over");
}
}
2. If the "main" method calls a method that throws an Exception as on line 1 below, and the call to line 1 is handled using a try-catch block (as on line 2 below), the exception is caught and "Over" will be printed.
public class TestClass {
public static void doStuff() throws Exception{// line 1
System.out.println("Doing stuff...");
if(Math.random() > 0.4){
throw new Exception("Too high!");
}
System.out.println("Done stuff.");
}
public static void main(String[] args) {
try { // line 2
doStuff();
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println("Over");
}
}
Summary:
1) throws Exception from "main" will enable the programmer to call the method on line 1, but the Exception will be propagated up the stack.
2) If you use a try-catch block, the exception will be caught and output will continue after the "catch" statement. (You are handling the exception where it occurs.)
(Exception e)
Exceptions are represented by objects.
All Java exceptions are instances of subclasses of class Exception .
We will get to all the different types of Java exceptions by the end of this section. For now, just keep in mind that the particular exception instance which gets created and thrown indicates the type of error that occurred. The parameter following the catch keyword indicates the particular exception your code will handle in that catch block. By indicating instances of class Exception in the above example (rather than indicating an instance of a subclass of class Exception ), that catch block will handle all exceptions (that is, instances of class Exception or any of its subclasses). You can, and you almost always should , indicate you would like to catch only a particular type of exception. For example, to catch only exceptions relating to number-formatting problems, you could write:
try{
// execute code here
}
catch(NumberFormatException e) {
// handle number format exceptions here
}
The above code indicates if any other exceptions are thrown (that is, anything other than an instance of NumberFormatException ), the exception will not be caught and handled here. That means Java will continue to look for error-handling code by looking through the call stack, or if it does not find one, Java will handle the exception itself (and you know that means the game will end). By handling only those exceptions you specifically anticipate, you will be certain not to hide other occurring errors that you are not aware of.