Lab Exercises - JAVA
Lab Exercises - JAVA
Lab Exercises - JAVA
Lab Manual
CPCS203
Programming II
(Object-oriented)
1432/1433H
Lab - 7
Learning Procedure
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. .…………………………………………….. ..…………………………….
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.
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;
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
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
Output:
in A...
java.lang.Exception: C is exceptional
in main...
java.lang.Exception: C is exceptional
Compile the program and examine the results. Does your code continue to
have problems?
Compile the program and examine the results. Does your code continue to
have problems?
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:
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) {
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
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.
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);
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.
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.