java try catch throw code example

Example 1: java try catch

try {
  // Code that may have error
} catch(ErrorName e){
  // Another code
}

Example 2: try catch java

public class MyClass {
  public static void main(String[ ] args) {
    try {
      int[] myNumbers = {1, 2, 3, 4, 5, 6};
      System.out.println(myNumbers[10]);
    } catch (Exception e) {
      System.out.println("Something went wrong. check again");
    }
  }
}

Example 3: java how to throw exception

public class ThrowException{
  public static void main(String [] args) throws Exception{ 
    //throws Exception line is needed if not using try-catch block
    throw new Exception("Errmessage");
  }
}

Example 4: java throw an exception

public static void main(String[] args) {
	Scanner kb = new Scanner(System.in);
    System.out.println("Enter a number");
    try {
    	double nb1 = kb.nextDouble();
    	if(nb1<0)
        	throw new ArithmeticException();
        else System.out.println( "result : " + Math.sqrt(nb1) );
    } catch (ArithmeticException e) {
        System.out.println("You tried an impossible sqrt");
    }
}

Example 5: throw error java

throw new java.lang.Error("this is very bad");
throw new java.lang.RuntimeException("this is not quite as bad");

Tags:

Cpp Example