Title: Exceptions First Examples
Course: CPS 261: Advanced Java Concepts ~ DL & MM MASTER

Exception First Examples

1. In the associated video we will create some simple examples:
  - Cause an exception(how about div/0) and see what happens if you don't catch it.
  - Cause the exception again and now catch it.
  - Cause an exception in another method and catch it at the main level and also try out catching at the method level.
2. In the associated video, we will create from scratch and go over the following example:

import java.util.InputMismatchException;
import java.util.Scanner;


public class Test {

    Scanner keyboard = new Scanner(System.in);

    int divideByZero(int num, int div)
    {
        try
        {
            return num/div;
        }
        catch (ArithmeticException e)
        {
            System.out.println("We caught our divide by zero error "+ e);
            return -1;
        }
    }

    int divideByZero2(int num, int div)
    {
            return num/div;
    }

    int readInteger()
    {
        boolean goodInput = false;
        int retValue=-1;

        while(!goodInput)
        {
            try
            {
                retValue = keyboard.nextInt();
                goodInput = true;
            }
            catch (InputMismatchException e)
            {
                System.out.println("Your integer was bad, try again");
                keyboard.next();
            }
        }
        return retValue;
    }



    public static void main(String[] args) {
        Test t = new Test();


        try
        {
            System.out.println("Enter in divisor ");
            int divisor = t.readInteger();

            int x = t.divideByZero(10, 1);
            x = t.divideByZero(20, divisor);
            x = t.divideByZero2(10, 1);
            x = t.divideByZero2(20, divisor);  // We expect to get an exception here


        }
        catch (ArithmeticException e)
        {
            System.out.println("Caught divide by zero in main: " + e);
        }

        System.out.println("Normal exit from my routine");


    }

}


	


Last Updated: July 27, 2013