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...
What is the java root class for exceptions? java.lang.throw java.lang.exceptions java.lang.errors java.lang.Throwable Which statement about exceptions...
What is the java root class for exceptions? java.lang.throw java.lang.exceptions java.lang.errors java.lang.Throwable Which statement about exceptions is NOT true. Exception handling enables a program to deal with errors during execution. Exceptions are compile time errors. Exceptions are thrown from a method. An exception is an Exceptions can be primitives or objects. True False "try-with-resources" syntax is used to ___________________. automatically close the files used in the program. throw an exception for a memory related error. all of the above validate...
*OBJECT ORIENTED PROGRAMMING* JAVA PROGRAMMING GOAL: will be able to throw and catch exceptions and create...
*OBJECT ORIENTED PROGRAMMING* JAVA 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...
*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...
A question about exceptions, the language is JAVA. The purpose is writing a program that reads...
A question about exceptions, the language is JAVA. The purpose is writing a program that reads a string from the keyboard and tests whether it contains a valid time. Display the time as described below if it is valid, otherwise display a message as described below. The input date should have the format hh:mm:ss (where hh = hour, mm = minutes and ss = seconds in a 24 hour clock , for example 23:47:55). Here are the input errors (Exceptions)...
Java Programming In this assignment we are going to create our own programming language, and process...
Java Programming In this assignment we are going to create our own programming language, and process it Java. programming language has 6 commands enter add subtract multiply divide return enter, add, subtract, multiply, divide all take 1 parameter (a double value). return takes no parameters.
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT