0% found this document useful (0 votes)
10 views8 pages

CS-2301 Lab (9) 422

The document outlines a lab exercise for students in a computer science course focused on practicing exception handling in Java. It includes multiple coding examples demonstrating various types of exceptions, such as ArrayIndexOutOfBoundsException and ArithmeticException, as well as custom exceptions like InsufficientFundsException. Additionally, it covers the use of assertions and chained exceptions, providing a comprehensive overview of exception management in Java programming.

Uploaded by

ovafi4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views8 pages

CS-2301 Lab (9) 422

The document outlines a lab exercise for students in a computer science course focused on practicing exception handling in Java. It includes multiple coding examples demonstrating various types of exceptions, such as ArrayIndexOutOfBoundsException and ArithmeticException, as well as custom exceptions like InsufficientFundsException. Additionally, it covers the use of assertions and chained exceptions, providing a comprehensive overview of exception management in Java programming.

Uploaded by

ovafi4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

LAB Experiments

‫ هـ‬1442 ‫الفصل الدراسى الثاني للعام الجامعي‬ ‫جامعة األمير سطام بن عبد العزيز‬
CS-2301 :‫المقرر‬ ‫كلية اآلداب والعلـوم بوادي الدواسر‬
78: ‫الشعبة‬ ‫ الرابع‬:‫المستوي‬ ‫قســـم علوم الحاسب‬
Lab-9

.............................................‫الرقم الجامعي‬ .........................................................................‫اسم الطالب‬


In this lab students will practice the following:
Practice Exceptions
Practice those examples:

1- Excute the follwing program:


import java.io.*;
public class ExcepTest {
public static void main(String args[]) {
try {
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}

2- Excute the follwing program:


// An application that attempts to divide by zero.
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; // possible division by zero
} // end method quotient

public static void main( String args[] )


{
Scanner scanner = new Scanner( System.in ); // scanner for input
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

3-

// 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
catch ( ArithmeticException arithmeticException )
{
System.err.printf( "\nException: %s\n", arithmeticException );
System.out.println(
2
Mr. Asad Abd Elrashid
"Zero is an invalid denominator. Please try again.\n" );
} // end catch
} while ( continueLoop ); // end do...while
} // end main
} // end class DivideByZeroWithExceptionHandling

4-

// Demonstration of the try...catch...finally exception handling


// mechanism.

public class UsingExceptions


{
public static void main( String args[] )
{
try
{
throwException(); // call method throwException
} // end try
catch ( Exception exception ) // exception thrown by throwException
{
System.err.println( "Exception handled in main" );
} // end catch

doesNotThrowException();
} // end main

// demonstrate try...catch...finally
public static void throwException() throws Exception
{
try // throw an exception and immediately catch it
{
System.out.println( "Method throwException" );
throw new Exception(); // generate exception
} // end try
catch ( Exception exception ) // catch exception thrown in try
{
System.err.println(
"Exception handled in method throwException" );
throw exception; // rethrow for further processing

// any code here would not be reached, exception rethrown in catch

} // end catch
finally // executes regardless of what occurs in try...catch
{
System.err.println( "Finally executed in throwException" );
} // end finally
// any code here would not be reached

} // end method throwException

// demonstrate finally when no exception occurs


public static void doesNotThrowException()
{
try // try block does not throw an exception
{
System.out.println( "Method doesNotThrowException" );
} // end try
catch ( Exception exception ) // does not execute
{
System.err.println( exception );
} // end catch
finally // executes regardless of what occurs in try...catch
{
System.err.println(
"Finally executed in doesNotThrowException" );
} // end finally

System.out.println( "End of method doesNotThrowException" );


} // end method doesNotThrowException
} // end class UsingExceptions

Task:

1- // File Name InsufficientFundsException.java


import java.io.*;
public class InsufficientFundsException extends Exception {
private double amount;

public InsufficientFundsException(double amount) {


this.amount = amount;
}
public double getAmount() {
return amount;
}
}
***********************************************************
// File Name CheckingAccount.java
import java.io.*;
public class CheckingAccount {
private double balance;
private int number;
4
Mr. Asad Abd Elrashid
public CheckingAccount(int number) {
this.number = number;
}
public void deposit(double amount) {
balance += amount;
}

public void withdraw(double amount) throws InsufficientFundsException {


if(amount <= balance) {
balance -= amount;
}else {
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}
public double getBalance() {
return balance;
}
public int getNumber() {
return number;
}
}
***************************************************************
// File Name BankDemo.java
public class BankDemo {
public static void main(String [] args) {
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);
try {
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
} catch (InsufficientFundsException e) {
System.out.println("Sorry, but you are short $" + e.getAmount());
e.printStackTrace();
}
}
}

2-
// Uses assert to check that an absolute value is positive
import java.util.Scanner;
public class AssertTest
{
public static void main( String args[] )
{
Scanner input = new Scanner( System.in );
System.out.print( "Enter a number between 0 and 10: " );
int number = input.nextInt();
// assert that the absolute value is >= 0
assert ( number >= 0 && number <= 10 ) : "bad number: " + number;
System.out.printf( "You entered %d\n", number );
} // end main
} // end class AssertTest +

3-
Find output of the following code:
// Demonstrating getMessage and printStackTrace from class Exception.
public class UsingExceptions
{
public static void main( String args[] )
{
try
{
method1(); // call method1
} // end try
catch ( Exception exception ) // catch exception thrown in method1
{
System.err.printf( "%s\n\n", exception.getMessage() );
exception.printStackTrace(); // print exception stack trace
// obtain the stack-trace information
StackTraceElement[] traceElements = exception.getStackTrace();

System.out.println( "\nStack trace from getStackTrace:" );


System.out.println( "Class\t\tFile\t\t\tLine\tMethod" );
// loop through traceElements to get exception description
for ( StackTraceElement element : traceElements )
{
System.out.printf( "%s\t", element.getClassName() );
System.out.printf( "%s\t", element.getFileName() );
System.out.printf( "%s\t", element.getLineNumber() );
System.out.printf( "%s\n", element.getMethodName() );
} // end for
} // end catch
} // end main

// call method2; throw exceptions back to main


public static void method1() throws Exception
{
method2();
} // end method method1

6
Mr. Asad Abd Elrashid
// call method3; throw exceptions back to method1
public static void method2() throws Exception
{
method3();
} // end method method2

// throw Exception back to method2


public static void method3() throws Exception
{
throw new Exception( "Exception thrown in method3" );
} // end method method3
} // end class UsingExceptions

4- Find output of the following code:

// Demonstrating chained exceptions.


public class UsingChainedExceptions
{
public static void main( String args[] )
{
try
{
method1(); // call method1
} // end try
catch ( Exception exception ) // exceptions thrown from method1
{
exception.printStackTrace();
} // end catch
} // end main
// call method2; throw exceptions back to main
public static void method1() throws Exception
{
try
{
method2(); // call method2
} // end try
catch ( Exception exception ) // exception thrown from method2
{
throw new Exception( "Exception thrown in method1", exception );
} // end try
} // end method method1

// call method3; throw exceptions back to method1


public static void method2() throws Exception
{
try
{
method3(); // call method3
} // end try
catch ( Exception exception ) // exception thrown from method3
{
throw new Exception( "Exception thrown in method2", exception );
} // end catch
} // end method method2

// throw Exception back to method2


public static void method3() throws Exception
{
throw new Exception( "Exception thrown in method3" );
} // end method method3
} // end class UsingC

8
Mr. Asad Abd Elrashid

You might also like