BE04000231 (OOP) Enrollment No :- 251263107020
Practical No : 06
Exercises :-
1. Write an exception class for a time of day that can accept only 24 hour representation of
clock hours. Write a java program to input various formats of timings and throw suitable
error messages.
Code :-
import [Link];
class InvalidTimeException extends Exception {
InvalidTimeException(String message) {
super(message);
}
}
class main {
static void checkTime(String time) throws InvalidTimeException {
try {
String[] parts = [Link](":");
int hour = [Link](parts[0]);
int minute = [Link](parts[1]);
if (hour < 0 || hour > 23)
throw new InvalidTimeException("Invalid Hour! Must be 0-23");
if (minute < 0 || minute > 59)
throw new InvalidTimeException("Invalid Minute! Must be 0-59");
[Link]("Valid Time: " + time);
} catch (NumberFormatException e) {
throw new InvalidTimeException("Time must be in HH:MM format");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter time (HH:MM): ");
String input = [Link]();
try {
checkTime(input);
} catch (InvalidTimeException e) {
[Link]("Error: " + [Link]());
}
BE04000231 (OOP) Enrollment No :- 251263107020
}
}
Output :-
2. Write a method for computing by doing repetitive multiplication. x and y are of type integer
and are to be given as command line arguments. Raise and handle exception(s) for invalid
values of x and y. Also define method main. Use finally in above program and explain its
usage.
Code :-
class main {
static int power(int x, int y) throws Exception {
if (y < 0)
throw new Exception("Exponent must be non-negative");
int result = 1;
for (int i = 1; i <= y; i++) {
result = result * x;
}
return result;
}
public static void main(String[] args) {
try {
if ([Link] != 2)
throw new Exception("Please provide two integers");
int x = [Link](args[0]);
int y = [Link](args[1]);
int ans = power(x, y);
[Link]("Result: " + ans);
} catch (NumberFormatException e) {
[Link]("Invalid input! Enter integers only.");
} catch (Exception e) {
BE04000231 (OOP) Enrollment No :- 251263107020
[Link]("Error: " + [Link]());
} finally {
[Link]("Program execution completed.");
}
}
}
Output :-
3. Write the Bin2Dec (string binary String) method to convert a binary string into a
decimal number. Implement the bin2Dec method to throw a NumberFormatException if
the string is not a binary string
Code :-
class main {
static int bin2Dec(String binaryString) {
for (int i = 0; i < [Link](); i++) {
if ([Link](i) != '0' &&
[Link](i) != '1') {
throw new NumberFormatException("Not a binary string");
}
}
int decimal = 0;
for (int i = 0; i < [Link](); i++) {
decimal = decimal * 2 + ([Link](i) - '0');
}
return decimal;
BE04000231 (OOP) Enrollment No :- 251263107020
public static void main(String[] args) {
try {
String binary = "101111";
int result = bin2Dec(binary);
[Link]("Decimal value: " + result);
} catch (NumberFormatException e) {
[Link]("Error: " + [Link]());
}
}
}
Output :-