Java examples for Object Oriented Design:Exception
You catch an exception by using a try statement, which has this general form:
try { statements that can throw exceptions } catch (exception-type identifier) { statements executed when exception is thrown }
Here's a program that divides two numbers and uses a try/catch statement to catch an exception if the second number turns out to be zero:
public class Main { public static void main(String[] args) {//www. ja v a 2 s . c om int a = 5; int b = 0; try { int c = a / b; // but you try it anyway } catch (ArithmeticException e) { System.out.println("Oops, you can't divide by zero."); } } }