Java try catch to catch Exception

www.laut‮rut‬i.com
Java try catch to catch Exception

Syntax:

try{
  
} catch(Exception e){
  
}

Example1:

/**
 * @author lautturi.com 
 * Java example:catch exception in java
 */

public class Lautturi {

	public static void main(String[] args) {

		try {
			int[] myNumbers = { 1, 2, 3 };
			System.out.println(myNumbers[3]);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			System.out.println(e);
		}

	}
}

output:

Index 3 out of bounds for length 3
java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

Example2:

/**
 * @author lautturi.com 
 * Java example: try catch example
 */

public class Lautturi {

	public static void main(String[] args) {

		try {
			System.out.println( 100/0 );
		} catch (Exception e) {
			System.out.println(e.getMessage());
			System.out.println(e);
		}

	}
}

output:

/ by zero
java.lang.ArithmeticException: / by zero

Exception in thread "main" java.lang.ArithmeticException: / by zero
at hello.Lautturi.main(Lautturi.java:68)
Created Time:2017-09-23 13:35:47  Author:lautturi