Nothing Special   »   [go: up one dir, main page]

Lab Exercises - JAVA

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

KING ABDULAZIZ UNIVERSITY

Faculty of Computing & Information Technology


Department of Computer Science

Lab Manual

CPCS203
Programming II
(Object-oriented)
1432/1433H

Lab - 7

Learning Procedure

1) Stage J (Journey inside-out the concept)


2) Stage a1 (apply the learned)
3) Stage v (verify the accuracy)
4) Stage a2 (assess your work)
Term I
2011 Lab-7: Exceptions and Assertions

Laboratory 7:

Statement Purpose:
This lab will give you practical implementation of different types of Exceptions
and Assertions in java.

Activity Outcomes:
This lab teaches you the following topics:
 Improve the reliability of code by incorporating exception-handling and
assertion mechanisms.
 Write methods that propagate exceptions.
 Implement the try-catch blocks for catching and handling exceptions.
 Write programmer-defined exception classes.

Instructor Note:
As pre-lab activity, read Chapter 8 from the book (An Introduction to Object-
Oriented Programming with Java, 4th Edition by C. THOMAS WU (Book’s
website www.mhhe.com/wu), and also as given by your theory instructor.

Names I.D.

1. .……………..………………………………. ………………………………

2. ..…………………………………………….. ………………………………

3. .……………………………………………... ………………………………

4. .…………………………………………….. ..…………………………….

CPCS203 – The Lab Note Lab-7 1


Term I
2011 Lab-7: Exceptions and Assertions

1) Stage J (Journey)

Introduction
Exception: handling is a very important yet often neglected aspect of writing
robust software. When an error occurs in a Java program it usually results in an
exception being thrown. How you throw, catch and handle these exception
matters. Runtime errors appear in Java as exceptions, exception is a special
type of classes that could be thrown to indicate a runtime error and provide
additional data about that error. If a method is declared to throw an exception,
any other method calls it should deal with this exception by throwing it (if it
appears) or handle it.

Three categories of errors (syntax errors, runtime errors, and logic errors):

1. Syntax errors arise because the rules of the language have not been
followed. They are detected by the compiler.
2. You can use the debugging techniques to find logic errors.
3. Exception handling to deal with runtime errors and using assertions to
help ensure program correctness.

Exception: is an indication of a problem that occurs during a program's


execution. Example: Divide By Zero Without Exception Handling.

Assertion: is a simple check assumption made at the beginning of the


program to ensure the program is true throughout provided by the Java
language. For example, the range of age should be in between 18 and above;
or cannot be more than 50.

CPCS203 – The Lab Note Lab-7 2


Term I
2011 Lab-7: Exceptions and Assertions

2) Stage a1 (apply)

Lab Activities:
Activity 1:
An application that attempts to divide by zero.
First we demonstrate what happens when errors arise in an application that
does not use exception handling
import java.util.Scanner;

public class DivideByZeroNoExceptionHandling {


// demonstrates throwing an exception when a divide-by-zero
occurs

public static int quotient( int numerator, int denominator ) {

return numerator / denominator;


}
public static void main( String args[] ) {

Scanner scanner = new Scanner( System.in );


System.out.print( "Please enter an integer numerator: " );
int numerator = scanner.nextInt();
System.out.print( "Please enter an integer denominator: " );
int denominator = scanner.nextInt();
int result = quotient( numerator, denominator );
System.out.printf( "\nResult: %d / %d = %d\n", numerator,
denominator, result );
} // end main
} // end class DivideByZeroNoExceptionHandling

CPCS203 – The Lab Note Lab-7 3


Term I
2011 Lab-7: Exceptions and Assertions

Activity 2:
//DivideByZeroWithExceptionHandling.java
//An exception-handling example that checks for divide-by-zero
import java.util.InputMismatchException;
import java.util.Scanner;
public class DivideByZeroWithExceptionHandling
{
// demonstrates throwing an exception when a divide-by-
zero occurs
public static int quotient( int numerator, int
denominator )
throws ArithmeticException
{
return numerator / denominator; // possible division
by zero
} // end method quotient
public static void main( String args[] )
{
Scanner scanner = new Scanner( System.in ); // scanner
for input
boolean continueLoop = true; // determines if more
input is needed
do
{
try // read two numbers and calculate quotient
{
System.out.print( "Please enter an integer
numerator: " );
int numerator = scanner.nextInt();
System.out.print( "Please enter an integer
denominator: " );
int denominator = scanner.nextInt();
int result = quotient( numerator, denominator );
System.out.printf( "\nResult: %d / %d = %d\n",
numerator,
denominator, result );
continueLoop = false; // input successful; end
looping
} // end try

catch ( InputMismatchException inputMismatchException )


{
System.err.printf( "\nException: %s\n",
inputMismatchException );
scanner.nextLine(); // discard input so user can
try again
System.out.println(
"You must enter integers. Please try again.\n"
);
} // end catch
CPCS203 – The Lab Note Lab-7 4
Term I
2011 Lab-7: Exceptions and Assertions

catch ( ArithmeticException arithmeticException )


{
System.err.printf( "\nException: %s\n",
arithmeticException );
System.out.println(
"Zero is an invalid denominator. Please try
again.\n" );
} // end catch
} while ( continueLoop ); // end do...while
} // end main
} // end class DivideByZeroWithExceptionHandling

Activity 3:
Go to ABC java code below and edit the ABC class. Examine the code and
predict what will happen if you compile this program.

Compile the program and examine the compiler error messages. What is the
problem with this code?

Example1:

ABC class program explains the concept of exceptional handling and throwing
an exception and catching exception.
import java.util.*;
import javax.swing.*;
class ABC {
CPCS203 – The Lab Note Lab-7 5
Term I
2011 Lab-7: Exceptions and Assertions

public static void main(String [] args)


{
try {
A();
B();
}
catch(Exception e){
System.out.println("in main...");
System.out.println(e);
}
}
public static void A(){
try {
B();
} catch(Exception e) {
System.out.println("in A...");
System.out.println(e);
}
}
public static void B()throws Exception
{
C();
}
public static void C()throws Exception{
throw new Exception("C is exceptional");
}
}

Output:
in A...
java.lang.Exception: C is exceptional
in main...
java.lang.Exception: C is exceptional

1. Add a throws Exception modifier to the declaration of the method C().


Predict what will happen when you compile your program with this change.

Compile the program and examine the results. Does your code continue to
have problems?

2. Add a throws Exception modifier to the declaration of the method B().


Predict what will happen when you compile your program with this change.

Compile the program and examine the results. Does your code continue to
have problems?

CPCS203 – The Lab Note Lab-7 6


Term I
2011 Lab-7: Exceptions and Assertions

3. Predict what will be output when you compile and run your program with
the change described above. Run the program and be prepared to explain your
results.

4. In your code for main, add a call to method C() immediately after the calls to
methods A() and B() in the try part of the try-catch block. Predict what will be
output when you compile and run your program with this change. Run the
program and be prepared to explain your results.

5. Change method B() so that it catches any exception thrown by the call to
method C(). When B() catches an exception, it should throw a new exception
that it constructs with the text "B is even more exceptional."

Make this change to your code and predict what will happen when you
compile and run your program. Compile and run it and examine your results.

6. Call Lab Instructor over when you are ready to show him your results and
explain them.

Finally, in your ABC class modify the C() method by removing the throw
statement, replacing it with the statement System.out.println("in C..."). Predict
what will happen when you run your modified program.

Compile and run your modified program and examine your results.

7. Call Lab Instructor over when you are ready to show him
Example 2:

Program explains the concept of exceptional handling and throwing an


exception and catching exception. Predict what will happen when you
compile your program with this change. Compile the program and examine
the results. Does your code continue to have problems?
import java.util.*;
import javax.swing.*;
class ABC {
public static void main(String [] args)
{
try {
A();
B();
C();
}
CPCS203 – The Lab Note Lab-7 7
Term I
2011 Lab-7: Exceptions and Assertions

catch(Exception e){
System.out.println("in main...");
System.out.println(e);
} }
public static void A(){
try {
B();
} catch(Exception e) {
System.out.println("in A...");
System.out.println(e);
} }
public static void B()throws Exception{
try {
C();
}
catch(Exception e){
System.out.println(e.getMessage()); //
System.out.println(e);
throw new Exception("B is even more exceptional");
}
}
public static void C()throws Exception{
throw new Exception("C is exceptional");
}
}

Example 3:

Predict what will be output when you compile and run your program with
the change described above. Run the program and be prepared to explain
your results.
import java.util.*;
import javax.swing.*;
class ABC {
public static void main(String [] args)
{
try {
A();
B();
C();
}
catch(Exception e){
System.out.println("in main...");
System.out.println(e);
} }
public static void A(){
try {
B();
} catch(Exception e) {

CPCS203 – The Lab Note Lab-7 8


Term I
2011 Lab-7: Exceptions and Assertions

System.out.println("in A...");
System.out.println(e);
} }
public static void B()throws Exception{
try {
C();
}
catch(Exception e){
System.out.println(e.getMessage()); //
System.out.println(e);
throw new Exception("B is even more exceptional");
}
}
public static void C()throws Exception{
//throw new Exception("C is exceptional");
System.out.println("in C...");
}
}

Activity 4:
In this Example We, defined a public class 'Mark Assert Demo' Inside the class
we define the static variable i.e. maximum marks to be 100, changes is another
static variable, The main static ( ) method has assumption of maximum marks
i.e. 40,if the marks come below to 40,the code will show you
java.lang.AssertionError and display the Marks is below than 40 on the
command prompt.
public class MarkAssertDemo
{
static float maximummarks=100;
static float changes(float mark)
{
maximummarks=maximummarks-mark;
System.out.println("The maximummark is:" +
maximummarks);
return maximummarks;
}
public static void main(String args[])
{
float g;
for(int i=0;i<5;i++)
{
g=changes(15);
assert maximummarks>=40.00:"marks is below 40.";
}
}
}
CPCS203 – The Lab Note Lab-7 9
Term I
2011 Lab-7: Exceptions and Assertions

Output on Command Prompt:


The maximummark is:85.0
The maximummark is:70.0
The maximummark is:55.0
The maximummark is:40.0
The maximummark is:25.0
Exception in thread "main" java.lang.AssertionError:
marks is below 40.
at MarkAssertDemo.main(MarkAssertDemo.java:16)

Task 1: In NetBeans turn on the Assertion by following these steps:


Turning runtime assertion checking on

 Right click on the project icon in the Project panel at the left.
 Select Properties at the bottom of the drop-down menu.
 Click on the Run choice in the left panel.

In the VM Options text field at the right, enter "-ea" (without the quotes). "ea"
stands for enable assertions. VM stands for Virtual Machine in this case, not
virtual memory.

CPCS203 – The Lab Note Lab-7 10


Term I
2011 Lab-7: Exceptions and Assertions

3) Stage v (verify)
Home Exercises:
1. Point out the problem in the following code. Does the code throw any
exceptions?
long value = Long.MAX_VALUE + 1;
System.out.println(value);

2. What is the purpose of declaring exceptions? How do you declare an


exception, and where? Can you declare multiple exceptions in a method
declaration?

3. What is the printout of the following code?


public class Test {
public static void main(String[] args) {
try {
int value = 30;
if (value < 40)
throw new Exception("value is too small"); }
catch (Exception ex) {
System.out.println(ex.getMessage()); }
System.out.println("Continue after the catch block"); }
}

What would be the printout if the line?


int value = 30; is changed to int value = 50;

4. Suppose that statement2 causes an exception in the following try-catch


block:
try { statement1;
statement2;
statement3; }
catch (Exception1 ex1) {
}
catch (Exception2 ex2) {
}
statement4;

Answer the following questions:


Will statement3 be executed?
If the exception is not caught, will statement4 be executed?
If the exception is caught in the catch block, will statement4 be executed?
If the exception is passed to the caller, will statement4 be executed?

CPCS203 – The Lab Note Lab-7 11


Term I
2011 Lab-7: Exceptions and Assertions

5. Write a program that count how many prime numbers between minimum
and maximum values provided by user. If minimum value is greater than or
equal to maximum value, the program should throw a InvalidRange
exception and handle it to display a message to the user on the following
format:Invalid range: minimum is greater than or equal to maximum.

For example, if the user provided 10 as maximum and 20 as minimum, the


message should be: Invalid range: 20 is greater than or equal to 10.

4) Stage a2 (assess)
Lab Report:
The laboratory report of this lab (and also all the following labs in this manual)
should include the following items/sections:

 A cover page with your name, course information, lab number and title,
and date of submission.
 A summary of the addressed topic and objectives of the lab.
 Implementation: a brief description of the process you followed in
conducting the implementation of the lab scenarios.
 Results obtained throughout the lab implementation, the analysis of these
results, and a comparison of these results with your expectations.
 Answers to the given exercises at the end of the lab. If an answer
incorporates new graphs, analysis of these graphs should be included here.
 A conclusion that includes what you learned, difficulties you faced, and any
suggested extensions/improvements to the lab.

Note: only a softcopy is required for both homework and report, please do not
print or submit a hard copy.

CPCS203 – The Lab Note Lab-7 12

You might also like