Question

In: Computer Science

In-Class coding exercise: (try - catch) (pass / fail) The purpose of this in-class coding exercise...

In-Class coding exercise: (try - catch) (pass / fail)

The purpose of this in-class coding exercise is to simulate various exception conditions using the program provided.

package com.InClass;
/*
* This program demonstrates the ability of catching different types of exceptions"
* You will have to modify the method() codes to trigger various/different exceptions.
* inClass Coding ( you will have to remove (comment out) the previous error condition before moving to trigger the next)
* 1) throw a myExcept exception (this is defined with an extends to Exception (see code)
* 2) use method () to trip a Arithmetic exception
* 3) use method () to trip a nullPointException
* 4) use method () call to trip a runtime exception
* 5) inside the myExcept error to inject an arithmetic error and watch it behave differently from step1 22
*
*/
public class TestExceptions {
   public static void main(String[] args) {
       try {
           // throw myException() first.
  
             
            method();
            System.out.println(" after the method call");
       }
       catch (MyExcept ex){
           System.out.println(" MyExcept error");
             
       }
       catch (ArithmeticException ex){
           System.out.println(" ArithmeticEx error");
             
       }
       catch (NullPointerException ex) {
           System.out.println(" nullPointException !!! ");
       }
       catch (IndexOutOfBoundsException e) {
           System.out.println(" index out of bounds...");
       }
       catch (RuntimeException ex ) {
           System.out.println(" Runtime exception");
           System.out.println(ex.getMessage());
             
       }
       catch (Exception e ) {
           System.out.println(" Exception");     
       }

       finally {
       System.out.println(" finally After the catch");
       }
   }
     
   static void method() throws Exception {

// create ArithmeticException
         
         
         
// create RuntimeExceptiom         
         

         
         
// create a null point exception here -- fix the exception above first

         
         
         
// create a ClassCastException here which is NOT on catch "watch" listed above


//   throw new Exception(); // trigger an Exceptiom
   }
}
class MyExcept extends Exception { // creating your custome error
   MyExcept(){
//       int y = 1/0; // uncomment this line to introduce an aritmetic exception inside your MyExcept
   System.out.println(" inside my custome MyExcept");
   }

}

Please complete the missing exceptions. Ignore the spellings mistakes/grammer, it's how the professor writes.

Instructions might be a bit hard to follow so please bear that in mind. Complete as much as possible.

Thank you.

Solutions

Expert Solution

I have implemented all the comments in the method() function and also provided comments so that you can follow.

You need to run the program several times running each exception at a time while commenting the rest. Hope this helps you, let me know for any questions or in case you have any follow up question.

Thanks : )

========================================================================

public class TestExceptions {

    public static void main(String[] args) {
        try {
            // when you want to run the below line please comment the next two lines
            // i.e comment method() and System.out.println(" after the method call");
            throw new MyExcept();

            // when you want to run the below 2 lines comment the above line i.e throw new MyExcept();
            //method();
            //System.out.println(" after the method call");

        } catch (MyExcept ex) {
            System.out.println(" MyExcept error");

        } catch (ArithmeticException ex) {
            System.out.println(" ArithmeticEx error");

        } catch (NullPointerException ex) {
            System.out.println(" nullPointException !!! ");
        } catch (IndexOutOfBoundsException e) {
            System.out.println(" index out of bounds...");
        } catch (RuntimeException ex) {
            System.out.println(" Runtime exception");
            System.out.println(ex.getMessage());

        } catch (Exception e) {
            System.out.println(" Exception");
        } finally {
            System.out.println(" finally After the catch");
        }
    }

    static void method() throws Exception {

        // create ArithmeticException
        // try to divide by zero; this will result in an Arithmetic Exception;
        int result = 5 / 0; // divide by zero will lead to an  Arithmetic Exception;

        // create RuntimeException;
        // we can create an empty string and access the 5th character;
        String empty = "";
        System.out.println("Try to print the 5th character: " + empty.charAt(4));


        // create a null point exception here -- fix the exception above first
        // Create an array pointing to null and then try to access the 1st element
        int[] nullArray = null;
        System.out.println("1st element value: " + nullArray[0]);

        // create a ClassCastException here which is NOT on catch "watch" listed above
        Object s = new String();
        Integer i = (Integer) s; // trying to cast a String to Integer class this will lead to ClassCastException

        //   throw new Exception(); // trigger an Exceptiom
        throw new Exception("Exception");
    }
}

class MyExcept extends Exception { // creating your custome error

    public MyExcept() {
      int y = 1/0; // uncomment this line to introduce an aritmetic exception inside your MyExcept
        System.out.println("Inside my custom MyExcept");
    }

}

==============================================================


Related Solutions

Exercise 2: Try-Catch Exercise Write a Java code that does the following: Create a class MyClass...
Exercise 2: Try-Catch Exercise Write a Java code that does the following: Create a class MyClass and create three methods myMethod1(), Method2() and Method3(). Invoke Method2() from Method1() and Method3() from Method2(). Write a code that can throw an exception inside myMethod3() and compile: File file=new File("filename.txt"); Scanner sc=new Scanner(file); You will get compilation errors now, as you are not handling a checked exception FileNotFoundException. Declare throws over myMethod3() and myMethod2(). You will need to add throws FileNotFoundException on myMethod()...
create your own function that wraps it with try catch. Pass in the string to parse,...
create your own function that wraps it with try catch. Pass in the string to parse, and the name of the field, put some logging in the catch How do I do this? say with this code segment? void readStudents() { //Scanner class object declare Scanner readStudentFile = null; //try block begin try { //open file readStudentFile = new Scanner(new File(".\\src\\test\\student.txt")); //loop until end of file while(readStudentFile.hasNextLine()) { String stu = readStudentFile.nextLine(); String[] eachStu; eachStu = stu.split(" "); students.add(new Student(eachStu[0],...
For practice using exceptions, this exercise will use a try/catch block to validate integer input from...
For practice using exceptions, this exercise will use a try/catch block to validate integer input from a user. Write a brief program to test the user input. Use a try/catch block, request user entry of an integer, use Scanner to read the input, throw an InputMismatchException if the input is not valid, and display "This is an invalid entry, please enter an integer" when an exception is thrown. InputMismatchException is one of the existing Java exceptions thrown by the Scanner...
What is Try and Catch in Java with example?
What is Try and Catch in Java with example?
Write a try/catch/finally clause to catch one or more specific Exception objects in Java.
Write a try/catch/finally clause to catch one or more specific Exception objects in Java.
. (a) The performance of staff is rated as excellent, satisfactory, pass or fail during the...
. (a) The performance of staff is rated as excellent, satisfactory, pass or fail during the evaluation period. Suppose the staff can be categorized as technical staff and administrative staff. A random 3 sample of 1000 staff were selected with their performance evaluation tabulated below. excellent satisfactory pass fail technical staff 50 250 200 30 adminstrative staff 60 200 200 10 Test whether there is an association between the category of staff and their performance evaluation at 1% level of...
Provide a description of the try .. catch statement. As part of your description you must...
Provide a description of the try .. catch statement. As part of your description you must describe how this statement can be used to handle errors and exceptions and include an example of try ... catch implemented to handle an error or exception within a Java program. Please Don't copy from someone else.
Java try and catch problem public void method1(){ int[] array = new int[1]; try{ array[2] =...
Java try and catch problem public void method1(){ int[] array = new int[1]; try{ array[2] = 0;} catch(ArithmeticException e){array[2] = 0} // ? finally{ return 0;}} Could you please tell me why the line with the question mark will not report an error?
Raising an Exception In the previous problem, you used a try/except statement to catch an exception....
Raising an Exception In the previous problem, you used a try/except statement to catch an exception. This problem deals with the opposite situation: raising an exception in the first place. One common situation in which you will want to raise an exception is where you need to indicate that some precondition that your code relies upon has not been met. (You may also see the assert statement used for this purpose, but we won’t cover that here.) Write a function...
A brief explanation is needed for these true/false questions. a) A method that contains a try-catch-finally...
A brief explanation is needed for these true/false questions. a) A method that contains a try-catch-finally structure may also have a “throws” declaration. b) An arithmetic exception such as division by zero can be avoided by careful programming while an I/O exception such as file not found may occur regardless of the precautions taken by the programmer. c) Lets assume that you create an object x of the Object class. You can assign any object (objects of other classes) to...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT