List of java Exception Example
1. Example to show Exception
2. Handing Exception (try, catch, finally)
3. Defining Custom Exception and Using it
Example to show Exception

public class ArrayException { public static void main(String[] args) { // TODO Auto-generated method stub int[] marks={34,35,36,39,40} ; for (int i=0; i<= marks.length; i++) { System.out.println(marks[i]); } } } |
Handing Exception (try, catch, finally)

import java.util.Scanner; public class ExampleException01 { public static void main(String[] args) { // TODO Auto-generated method stub try{ int a ; System.out.println("This is Monitor block"); Scanner sc1 = new Scanner(System.in); System.out.println("Please enter Dividend"); int b = sc1.nextInt(); System.out.println("Please enter Divisor"); int c = sc1.nextInt(); a = b/c ; System.out.println("Output is:"+a); } catch (Exception e) { System.out.println("This is a catch block"); System.out.println(e.getMessage()); System.out.println(e.getCause()); e.printStackTrace(); } finally{ System.out.println("This is a finally block"); } } } |
Defining Custom Exception and Using it

public class CustomException extends Exception // In-Sufficient Balance { private int reason_code; CustomException(String msg){ super(msg); } CustomException(int i1){ super("Reason Code"+ i1); reason_code = i1 ; } @Override public String toString() { String msg_str = "In-Sufficient Balance, Please enter less amount" ; return msg_str; } } package in.sisoft; import java.util.Scanner; public class BankAcUsingCustom { private float balance ; BankAcUsingCustom(float amt) { this.balance = amt ; } public float getBalance() { return balance; } public void setBalance(float balance) { this.balance = balance; } void withdraw_amt(float amt) throws CustomException{ if (amt > getBalance() ){ CustomException ce = new CustomException("In Sufficient Balance"); throw ce ; } else { setBalance(getBalance()- amt); System.out.println("Thanks for availing the service"); } } public static void main(String[] args){ float draw_amt ; BankAcUsingCustom ac1 = new BankAcUsingCustom(2500.0f); Scanner sc1 = new Scanner(System.in); System.out.println("Enter the amount to Withdraw"); draw_amt = sc1.nextFloat(); try{ ac1.withdraw_amt(draw_amt); } catch (Exception ce) { System.out.println(ce.getMessage()) ; } } } |