Lab 08

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Department of: Subject of:

Computer Systems Engineering Object Oriented Programming


Mehran University of Engineering Year 1st Semester 2nd
&Technology
Batch 23CS Duration 03
Hours
Jamshoro

Practical # 8

To practice programs using Exception Handling Mechanism

Objective

 To practice programs using Exception Handling Mechanism.

Tools
 Notepad++/CMD.

Keywords: Try, catch , throw , throws. Duration:03 hours

Write a Program that prompts the user to read Two Integers and Displays their Sum.
Program should prompt the user to read the number again if the input is incorrect (i.e. user
enters word or float point number).

import java.util.*;

public class Main {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num1, num2;

System.out.print("Enter the first integer: ");


while (!sc.hasNextInt()) {
System.out.println("Invalid input! Please enter an integer.");
sc.next();
System.out.print("Enter the first integer: ");
}
num1 = sc.nextInt();

System.out.print("Enter the second integer: ");


while (!sc.hasNextInt()) {
System.out.println("Invalid input! Please enter an integer.");
sc.next();
System.out.print("Enter the second integer: ");
}
num2 = sc.nextInt();

int sum = num1 + num2;


System.out.println("Sum of "+num1+" and "+num2+" is: "+sum);

}
}

OUTPUT

Write a Program that causes the JVM to throw an OutOfMemoryError and catches and
handles this error.

public class Main {


public static void main(String[] args) {
try {
int[] array=new int[Integer.MAX_VALUE];
} catch (OutOfMemoryError e) {
System.out.println("Caught OutOfMemoryError:
"+e.getMessage());
}
}
}

OUTPUT
Write a program that creates two classes, NoMatchException and TestException.
NoMatchException is a user-defined exception and TestException simply uses it.
TestException takes the input from the user and throws the object of NoMatchException if
the user provides “OOP” as input.

import java.util.Scanner;

class NoMatchException extends Exception {


public NoMatchException(String message) {
super(message);
}
}

class TestException {
public void userInput() throws NoMatchException {
Scanner sc = new Scanner(System.in);

System.out.print("Enter input: ");


String input = sc.nextLine();

if (input.equals("OOP")) {
throw new NoMatchException("Input matches 'OOP'");
} else {
System.out.println("Input: " + input);
}

}
}

public class Main {


public static void main(String[] args) {
TestException testException = new TestException();
try {
testException.userInput();
} catch (NoMatchException e) {
System.out.println("Caught NoMatchException: " +
e.getMessage());
}
}
}
OUTPUT

Rubrics Marks Obtained


0 1
Completeness & Accuracy

Timelines

Student ID: 23CS016

Subject Teacher: Dr. Irfan Ali Bhacho

Date: _______________

You might also like