The Try Block
The Catch Block
Syntax
try{ //Code vulnerable to exceptions } catch (Exception e){ //Show error to user in some way //Use e.getMessage() to get exact error message }
Flow Control
Example
public class Main { public static void main(String[] args) { try{ int a,b; a=100; b=a/0; } catch (Exception e){ System.out.println("Division by zero isn't possible"); } } }
In this program, two variables are declared namely, a and b. We assign some finite value to a, let’s say, 100. Now b stores the outcome of a divided by 0. Now since it’s impossible to divide any number by 0, ArithmaticException has occurred and the catch block gets the control which further shows the error as specified.