Java Exceptions  «Prev 

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.

Java 12 Pogramming
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.)