Question

In: Computer Science

This programming assignment involves learning about some common exceptions which occur in Java programs. Consider the...

This programming assignment involves learning about some common exceptions which occur in Java programs. Consider the following exception types:

NullPointerException

ArrayIndexOutOfBounds

Exception ClassCastException

IllegalArgumentException

Research what each exception type means and the conditions under which each occurs (thrown). Then write the following programs, one for each of the above-listed exception types:

  • A program which throws the exception (with a throw statement) and catches it displaying unique information about the exception. Name your programs <exception>Thrown.java

    <exception> is the name of the exception involved for example NullPointerExceptionThrown.java.

  • A program which causes the exception to be thrown (not with a throw statement) and catches it displaying unique information about the exception (ex. Name of class and method causing the exception). For example, for the NullPointerException, have your program create a situation which would cause this exception to be thrown. Name your programs <exception>Catch.java <exception> is the name of the exception involved for example NullPointerExceptionCatch.java.

    At the end you should have eight programs, four <exception>Thrown.java and four <exception>Catch.java. All files should be in the same directory.

Solutions

Expert Solution

1st file

NullPointerExceptions are exceptions that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object.

NullPointerExceptionThrown.java

public class NullPointerExceptionThrown {
   public static void hasCode(){
       System.out.println("Do Something");
   }

public static void main(String[] args) {
Object a = null;
a.hashCode();
}

}

Output:

2nd File:

NullPointerExceptionCatch.java
public class NullPointerExceptionCatch {
   public static void hasCode(){
       System.out.println("Do Something");
   }

public static void main(String[] args) {
try {
   Object a = null;
       a.hashCode();
} catch(NullPointerException e) {
System.out.println("NullPointerException.. Handled");
}
}

}

3rd File

If a request for a negative or an index greater than or equal to size of array is made, then the JAVA throws a ArrayIndexOutOfBounds Exception.

ArrayIndexOutOfBoundThrown.java

public class ArrayIndexOutOfBoundThrown{
   public static void main(String[] args) {
       int[] arr=new int[5];
       int i=0;
       System.out.println(arr[6]);
   }
}

4th File

ArrayIndexOutOfBoundCatch.java

public class ArrayIndexOutOfBoundCatch{
   public static void main(String[] args) {
       try{
int[] arr=new int[5];
           int i=0;
           System.out.println(arr[6]);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("Array Index is Out Of Bounds");
}
   }
}

5th File

if you are trying to typecast an object of class A into an object of class B, and they aren't compatible, you get a class cast exception.

classCastExceptionThrown.java


public class classCastExceptionThrown {

public static void main(String[] args) {

   Object i = Integer.valueOf(42);
               String s = (String)i;

}

}

6th File

classCastExceptionCatch.java


public class classCastExceptionThrown {

public static void main(String[] args) {
        try{
            Object i = Integer.valueOf(42);
               String s = (String)i;
        } catch(ClassCastException e) {
System.out.println("ClassCastException.. Handled");
}

}

}

7th File

The IllegalArgumentException is a good way of handling possible errors in your application’s code. This exception indicates that a method is called with incorrect input arguments.

IllegalArgumentExceptionThrown.java

import java.io.File;

public class IllegalArgumentExceptionThrown {

public static String createRelativePath(String parent, String filename) {
if(parent == null)
throw new IllegalArgumentException("The parent path cannot be null!");

if(filename == null)
throw new IllegalArgumentException("The filename cannot be null!");

return parent + File.separator + filename;
}

public static void main(String[] args) {
// The following command will be successfully executed.
System.out.println(IllegalArgumentExceptionThrown.createRelativePath("dir1", "file1"));
System.out.println();

// The following command throws an IllegalArgumentException.
System.out.println(IllegalArgumentExceptionThrown.createRelativePath(null, "file1"));
}

}
}

8th File

IllegalArgumentExceptionCatch.java

import java.io.File;

public class IllegalArgumentExceptionCatch {

public static String createRelativePath(String parent, String filename) {
if(parent == null)
throw new IllegalArgumentException("The parent path cannot be null!");

if(filename == null)
throw new IllegalArgumentException("The filename cannot be null!");

return parent + File.separator + filename;
}

public static void main(String[] args) {
// The following command will be successfully executed.
try{
System.out.println(IllegalArgumentExceptionCatch.createRelativePath("dir1", "file1"));
System.out.println();

// The following command throws an IllegalArgumentException.
System.out.println(IllegalArgumentExceptionCatch.createRelativePath(null, "file1"));
} catch (IllegalArgumentException e){
System.out.println("IllegalArgumentException Handled !!");
}

}
}


Related Solutions

This programming assignment involves learning about some of the common exceptions that occur in Java programs.
This programming assignment involves learning about some of the common exceptions that occur in Java programs. Consider the following exception types: NullPointerException ArrayIndexOutOfBoundsException ClassCastException IllegalArgumentException Research what each exception type means and the conditions under which each occurs (i.e., is thrown). Write programs that demonstrate each type of exception being thrown (one program per exception) and provide a screen capture of the output. You should write your code so that each exception type is forced to occur. Name your programs...
*OBJECT ORIENTED PROGRAMMING* GOAL: will be able to throw and catch exceptions and create multi-threaded programs....
*OBJECT ORIENTED PROGRAMMING* GOAL: will be able to throw and catch exceptions and create multi-threaded programs. Part I Create a class called Animal that implements the Runnable interface. In the main method create 2 instances of the Animal class, one called rabbit and one called turtle. Make them "user" threads, as opposed to daemon threads. Some detail about the Animal class. It has instance variables, name, position, speed, and restMax. It has a static boolean winner. It starts a false....
Java Programming II Homework 2-1 In this assignment you are being asked to write some methods...
Java Programming II Homework 2-1 In this assignment you are being asked to write some methods that operate on an array of int values. You will code all the methods and use your main method to test your methods. Your class should be named Array Your class will have the following methods (click on the method signatures for the Javadoc description of the methods): [ https://bit.ly/2GZXGWK ] public static int sum(int[] arr) public static int sum(int[] arr, int firstIndex, int...
Java Programming 5th edition Chapter 10 Inheritance Programs Part 1 Number 3 on page 719 which...
Java Programming 5th edition Chapter 10 Inheritance Programs Part 1 Number 3 on page 719 which creates a Point class with 2 instance variables; the xCoordinate and yCoordinate. It should have a default constructor and a values constructor. Also include a set method that sets both attributes, a get method for each attribute, and a method that redefines toString() to print the attributes as follows. point: (x, y) Part 2 Do number 4 on page 719 which creates a Circle...
JAVA programming - please answer all prompts as apart of 1 java assignment. Part A Create...
JAVA programming - please answer all prompts as apart of 1 java assignment. Part A Create a java class InventoryItem which has a String description a double price an int howMany Provide a copy constructor in addition to other constructors. The copy constructor should copy description and price but not howMany, which defaults to 1 instead. In all inheriting classes, also provide copy constructors which chain to this one. Write a clone method that uses the copy constructor to create...
PROGRAMMING LANGUAGE : JAVA Problem specification. In this assignment, you will create a simulation for a...
PROGRAMMING LANGUAGE : JAVA Problem specification. In this assignment, you will create a simulation for a CPU scheduler. The number of CPU’s and the list of processes and their info will be read from a text file. The output, of your simulator will display the execution of the processes on the different available CPU’s. The simulator should also display: -   The given info of each process -   CPU utilization - The average wait time - Turnaround time for each process...
JAVA PROGRAMMING For this assignment, review the successor method in BST. The successor of a node...
JAVA PROGRAMMING For this assignment, review the successor method in BST. The successor of a node is the node with the next highest value in the tree. The successor of the node with the largest value in a tree, is null. The algorithm to find the successor of a node is straight forward: if the node has a right subtree, the successor is the smallest node in that subtree (for that we use method minNode). Otherwise, we traverse the tree...
JAVA PROGRAMMING. In this assignment, you are to create a class named Payroll. In the class,...
JAVA PROGRAMMING. In this assignment, you are to create a class named Payroll. In the class, you are to have the following data members: name: String (5 pts) id: String   (5 pts) hours: int   (5 pts) rate: double (5 pts) private members (5 pts) You are to create no-arg and parameterized constructors and the appropriate setters(accessors) and getters (mutators). (20 pts) The class definition should also handle the following exceptions: An employee name should not be empty, otherwise an exception...
Programming Language: JAVA In this assignment you will be sorting an array of numbers using the...
Programming Language: JAVA In this assignment you will be sorting an array of numbers using the bubble sort algorithm. You must be able to sort both integers and doubles, and to do this you must overload a method. Bubble sort work by repeatedly going over the array, and when 2 numbers are found to be out of order, you swap those two numbers. This can be done by looping until there are no more swaps being made, or using a...
This is a programming assignment!!! Start with the Assignment3.java source code posted to Canvas. This code...
This is a programming assignment!!! Start with the Assignment3.java source code posted to Canvas. This code outputs the programmer’s name , prompts the user to enter two numbers (integers) and outputs their sum. Note: When you run the program, it expects you to enter two integer values (a counting or whole number like 1, 216, -35, or 0) Make the following changes/additions to the code: On line 11, change the String myName from “your full name goes here!!!” to your...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT