0% found this document useful (0 votes)
16 views7 pages

Java Exception Handling Lab Exercise

The document provides instructions for a laboratory exercise on exceptions in Java. It includes: - The objective is to demonstrate how to use exceptions, catch exceptions, and understand the advantage of exception handling. - Students should create a NetBeans project called "Lab009_" followed by their last and first name, and compress and upload the project file. - The document includes code samples and questions to test understanding of exceptions, such as how exceptions are handled, how to fix exception errors, and how exceptions can be thrown and caught.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views7 pages

Java Exception Handling Lab Exercise

The document provides instructions for a laboratory exercise on exceptions in Java. It includes: - The objective is to demonstrate how to use exceptions, catch exceptions, and understand the advantage of exception handling. - Students should create a NetBeans project called "Lab009_" followed by their last and first name, and compress and upload the project file. - The document includes code samples and questions to test understanding of exceptions, such as how exceptions are handled, how to fix exception errors, and how exceptions can be thrown and caught.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Computer Programming 2

Exception 1

Week010 - Exception
Laboratory Exercise 009

Objective/s:
At the end of this activity, you should be able to:
· Demonstrate how Exceptions will be used
· Understand how to catch the exceptions
· Learn the advantage of exception handing in an application

What to Prepare for the Activity:


 NetBeans IDE 8.2
 JDK8 (Java Development Kit 8)

Procedure:
 Create a NetBeans project for this activity. The project name should be as follows:
Project Name: Lab009_<lastname_firstname>
Example: Lab009_Blanco_Maria
 Compress the NetBeans project into .rar or .zip format and then upload to the link
provided in the LMS.
 Only NetBeans project compressed in .rar or .zip format will be accepted.

A. Given the following class:


public class MyClass {
public static void main(String[] args) {
int k=0;
try {
int i = 5/k;
} catch (Exception e) {
[Link]("3");
} catch (ArithmeticException e) {
[Link]("1");
} catch (RuntimeException e) {
[Link]("2");
return;

Assessments
} finally {
[Link]("4");
}
[Link]("5");
}
}

Test Stem / Question Choices

1: Run the class above. What was the A: Compile Error


result?
B: Runtime exception

C: Arithmetic exception

D: run perfectly

2: What needs to be done to remove the A: Make the catch clause catching Exception as the last catch
error in the class? clause

B: Remove the finally clause

C: Set the value of k to 1.

D: Nothing

3: Now that you have fixed the code above, A: It printed:


what is the new result? 1
4
5

B: It printed:
3
1
5

C: It printed:
Computer Programming 2
Exception 3

1
2
5

D: It printed:
5
Since it is correct to begin with.

B. Given the following program, which statements are true?


public class ExceptionLabExercise {
public static void main(String[] args) {
try {
[Link](args[0]);
} finally {

Assessments
[Link]("FINALLY");
}
}
}

C. Given the following classes,

public class TestClass {

public static void main(String[] args) throws A {


try {
f();
} finally {
[Link]("Done.");

Test Stem / Question Choices

4: Run the class above. What A: It printed finally then thrown


happens when you run with no ArrayIndexOutOfBoundsException
arguments?
B: It printed ArrayIndexOutOfBoundsException

C: It printed finally

D: Nothing happend

5: If an A: Check the length of the array before printing the


ArrayIndexOutOfBoundsExceptio arguments
n occurred, what is the best way
to handle this? B: Add a catch clause for the said exception

C: Always use finally clause in order to avoid


exceptions

D: Nothing. That Exception needs not be caught.

} catch (Exception1 e) {
throw e;
Computer Programming 2
Exception 5
}
}
}

public class Exception1 extends Throwable{}

Test Stem / Question Choices

6: What is the problem with the A: The finally statement must be preceeded by the
above code? catch clause

B: Exceptions cannot be extended

C: It is illegal to throw an exception

D: Nothing is wrong

7: What should be done with the A: Move the catch clause before the finally clause.
code?
B: Do not use Throwable as the supertype of
Exception 1.

C: Do not throw the exception.

D: Nothing is wrong

8: What happens after you have A: “Done” is printed and an exception is shown in
been able to fix the code? the stack

B: “Done” is printed

C: Exception is shown in the stack

D: Nothing is wrong

Assessments
public class JavaApplication1 {

public static void main(String[] args) {


RuntimeException exception = null;
throw exception;
}
}

Test Stem / Question Choices

9: What is the problem with the A: null exception cannot be thrown


above code?
B: the main method must be declared with throws
statement

C: It is illegal to throw an exception

D: Nothing is wrong

10: How should you fix the code? A: A & B


Choose from the following:
A. Instantiate the exception B: A only
B. Add a throws statement in the
method declaration C: B only

C. Do no throw the exception


D: All is correct
Computer Programming 2
Exception 7

Assessments

Common questions

Powered by AI

To correct the exception handling structure, rearrange the catch clauses to handle the most specific exceptions first. The catch block for ArithmeticException should come before the general Exception catch block. After rearranging the catch blocks, set the value of k to 1 to avoid exceptions. The output then will be "1 4 5".

Throwing a null RuntimeException is problematic because it results in a NullPointerException. To resolve this, instantiate the RuntimeException object before throwing it. This way, a valid exception object is used when the throw statement is executed.

The finally block ensures execution of necessary cleanup operations, regardless of whether an exception is thrown or not. It executes after try and catch blocks have run, ensuring that resource releasing or important final operations always occur.

The recommended approach is to check the length of the array before accessing its elements, which is effective because it ensures indices are valid, reducing the risk of trying to access an element outside the array's bounds.

Ensure that Exception1 extends the Exception class instead of Throwable, as this aligns with Java's convention for custom exceptions. Doing so allows the exception to be used in normal catch clauses without causing confusion or deviation from standard practices.

Using Throwable as a supertype for user-defined exceptions can lead to inappropriate handling, as Throwable encompasses both exceptions and errors. Instead, extending the Exception class is preferred, ensuring that scenarios requiring error handling aren't mistakenly considered exceptions. This maintains the semantic distinction between recoverable conditions and serious faults.

The output sequence is "3 4 5". Initially, an attempt is made to divide by zero, which triggers an ArithmeticException. Since the general Exception catch block comes first, it catches the ArithmeticException and prints "3". The finally block executes and prints "4". Finally, "5" is printed after exiting the try-catch-finally statement.

The order of catch blocks is crucial because Java checks them sequentially from top to bottom, catching the first applicable exception. If more general exceptions precede specific ones, the specific exceptions are never reached, leading to inefficient error handling and potential logic errors.

The issue with the TestClass is that the catch clause appears after the finally block, which is incorrect. The catch clause should precede the finally block. By moving the catch block above the finally block, the code will comply with Java's exception handling rules.

If executed without any command-line arguments, the program throws an ArrayIndexOutOfBoundsException. This occurs because args[0] is accessed without verifying if the args array contains any elements, leading to an invalid index access.

You might also like