0% found this document useful (0 votes)
0 views21 pages

Week 8

The document provides an overview of exception handling in Java, explaining what exceptions are, the keywords used for handling them, and the exception hierarchy. It includes practical examples of handling exceptions in various scenarios, such as reading user input, calculating averages, and validating data. Additionally, it discusses user-defined exceptions and best practices for managing exceptions effectively.

Uploaded by

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

Week 8

The document provides an overview of exception handling in Java, explaining what exceptions are, the keywords used for handling them, and the exception hierarchy. It includes practical examples of handling exceptions in various scenarios, such as reading user input, calculating averages, and validating data. Additionally, it discusses user-defined exceptions and best practices for managing exceptions effectively.

Uploaded by

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

1. What is an Exception in Java?

In Java, an exception is an event that disrupts the normal flow of a


program's execution. It typically occurs when something unexpected or
erroneous happens during the program's runtime. Exceptions can arise
due to various reasons such as invalid input, hardware failures, resource
unavailability, or logical errors in the code.

2. What are the exception handling keywords in Java?

Java's exception handling relies on keywords like "try," "catch," and


"finally" to manage errors gracefully during runtime. The "try" block
encloses code where exceptions might occur, while "catch" blocks handle
specific types of exceptions. The optional "finally" block ensures cleanup
code executes regardless of exceptions. "throw" allows developers to raise
exceptions, while "throws" in method signatures declares potential
exceptions.

3. Explain Java exception hierarchy?

In Java, the exception hierarchy begins with the Throwable class, which
has two main subclasses: Error and Exception. Error represents serious
system-level issues, while Exception is further divided into checked and
unchecked exceptions. Checked exceptions must be handled explicitly,
while unchecked exceptions indicate runtime errors and don't require
explicit handling.

4. Can we have an empty catch block?


Yes, it is possible to have an empty catch block in Java, although it's
generally discouraged. An empty catch block does not contain any code
within its braces and therefore does nothing when an exception occurs.
While it may suppress compiler warnings, it effectively hides potential
errors, making it difficult to diagnose and handle exceptions properly. It's
considered a best practice to include meaningful code within catch blocks
to handle exceptions appropriately, such as logging the error, providing
error messages, or taking corrective action.

5. What happens when an exception is thrown by the main method?

When an exception is thrown by the main method in Java, it can be caught


and handled within the main method using a try-catch block. If uncaught,
the exception results in the program terminating abruptly, possibly
displaying exception details, including the stack trace. Any associated
finally blocks are executed before termination, allowing for cleanup
operations.
In Lab

1. In this challenge, you must read an integer, a double, and a String from stdin, then print
the values according to the instructions in the Output Format section below. To make the
problem a little easier, a portion of the code is provided for you in the editor. Note: We
recommend completing Java stdin and stdout I before attempting this challenge.

import java.util.Scanner;

public class Solution {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);


int i=sc.nextInt();
double d=sc.nextDouble();
sc.nextLine();
String s=sc.nextLine();
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
}

Input (stdin)
42
3.1415
Welcome to HackerRank's Java tutorials!
Expected Output
String: Welcome to HackerRank's Java tutorials!
Double: 3.1415
Int: 42

2. Implement a Java program with a method to calculate and print the average of an array
of integers. The average should be calculated as the sum of all elements divided by the
total number of elements. Exception Handling:Handle the case where the array is empty
to avoid an arithmetic exception. If the array is empty, throw an ArithmeticException
with the message "Cannot calculate average of an empty array." Output Format:Print the
calculated average if the array is non-empty. If an empty array is encountered, catch the
ArithmeticException and print an error message.

public class AverageCalculator {

public static void main(String[] args) {

int[] numbers = {10, 20, 30, 40, 50}; // Sample array of integers

try {

double average = calculateAverage(numbers);

System.out.println("Average: " + average);

} catch (ArithmeticException e) {

System.out.println("Error: " + e.getMessage());

public static double calculateAverage(int[] arr) {

if (arr.length == 0) {

throw new ArithmeticException("Cannot calculate average of an empty array.");

int sum = 0;

for (int num : arr) {

sum += num;

return (double) sum / arr.length;

Input

int[] numbers = {10, 20, 30, 40, 50};


Output

Average: 30.

Input

int[] numbers = {};

Output

Error: Cannot calculate average of an empty array.

3.You are given an integer n, you have to convert it into a string. Please complete the partially
completed code in the editor. If your code successfully converts n into a string s the code will
print "Good job". Otherwise, it will print "Wrong answer". n can range between -100 to 100
inclusive. Sample Input 0 100 Sample Output 0 Good job
import java.util.*;
import java.security.*;
public class Solution {
public static void main(String[] args) {

DoNotTerminate.forbidExit();

try {
Scanner in = new Scanner(System.in);
int n = in .nextInt();
in.close();
//String s=???; Complete this line below
String s=Integer.toString(n);
//Write your code here

if (n == Integer.parseInt(s)) {
System.out.println("Good job");
} else {
System.out.println("Wrong answer.");
}
} catch (DoNotTerminate.ExitTrappedException e) {
System.out.println("Unsuccessful Termination!!");
}
}
}

//The following class will prevent you from terminating the code
using exit(0)!
class DoNotTerminate {

public static class ExitTrappedException extends SecurityExcepti


on {

private static final long serialVersionUID = 1;


}

public static void forbidExit() {


final SecurityManager securityManager = new SecurityManager() {
@Override
public void checkPermission(Permission permission) {
if (permission.getName().contains("exitVM")) {
throw new ExitTrappedException();
}
}
};
System.setSecurityManager(securityManager);
}
}

Input

42

Output

Good job
Post lab

1.The Calendar class is an abstract class that provides methods for converting between a specific
instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so
on, and for manipulating the calendar fields, such as getting the date of the next week.You are given
a date. You just need to write the method, getDay, which returns the day on that date. To simplify
your task, we have provided a portion of the code in the editor.

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

/*
* Complete the 'findDay' function below.
*
* The function is expected to return a STRING.
* The function accepts following parameters:
* 1. INTEGER month
* 2. INTEGER day
* 3. INTEGER year
*/

public static String findDay(int month, int day, int year)


{
java.time.LocalDate dt = java.time.LocalDate.of(year, mon
th, day);
return dt.getDayOfWeek().toString();

public class Solution {


public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new In
putStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new Fi
leWriter(System.getenv("OUTPUT_PATH")));

String[] firstMultipleInput = bufferedReader.readLine().r


eplaceAll("\\s+$", "").split(" ");

int month = Integer.parseInt(firstMultipleInput[0]);

int day = Integer.parseInt(firstMultipleInput[1]);

int year = Integer.parseInt(firstMultipleInput[2]);

String res = Result.findDay(month, day, year);

bufferedWriter.write(res);
bufferedWriter.newLine();

bufferedReader.close();
bufferedWriter.close();
}
}

Input

08 05 2015

Output

WEDNESDAY
Skill Session

1.Write a Java program that takes user input for two numbers, adds them, and handles the possibility
of an InputMismatchException. Perform the following steps:Use a Scanner to prompt the user to
enter the first number. Handle the potential InputMismatchException by catching the exception and
printing an error message. If the input for the first number is successful, proceed to prompt the user
to enter the second number. Again, handle the potential InputMismatchException for the second
number and print an appropriate error message. If both inputs are valid, calculate and print the sum
of the two numbers.

import java.util.InputMismatchException;

import java.util.Scanner;

public class AddNumbers {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

try {

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

int firstNumber = scanner.nextInt();

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

int secondNumber = scanner.nextInt();

int sum = firstNumber + secondNumber;

System.out.println("Sum: " + sum);

} catch (InputMismatchException e) {

System.out.println("Error: Invalid input. Please enter a valid integer.");

} finally {

scanner.close();

Input
Enter the first number: 10

Enter the second number: 20

Output

Sum: 30

Input

Enter the first number: abc

Error: Invalid input. Please enter a valid integer.


2. Exception handling is the process of responding to the occurrence, during computation, of
exceptions – anomalous or exceptional conditions requiring special processing – often changing the
normal flow of program execution. Java has builtin mechanism to handle exceptions. Using the try
statement, we can test a block of code for errors. The catch block contains the code that says what to
do if exception occurs. This problem will test your knowledge on try-catch block. You will be given
two integers x and y as input, you must compute x/y. If x and y are not 32-bit signed integers or if y is
zero, exception will occur, and you have to report it. Read sample Input/Output to know what to
report in case of exceptions.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

public static void main(String[] args) {


Scanner in = new Scanner(System.in);
try {
int a = in.nextInt();
int b = in.nextInt();
System.out.println(a/b);
} catch (java.util.InputMismatchException ime) {
System.out.println("java.util.InputMismatchException");
} catch (java.lang.ArithmeticException ae) {
System.out.println("java.lang.ArithmeticException: / by zero");
}
}
}

Input

10

Output

3
3.You are required to compute the power of a number by implementing a calculator. Create a class
MyCalculator which consists of a single method long power (int, int). This method takes two integers,
n and p, as parameters and finds np. If either n or p is negative, then the method must throw an
exception which says, "n or p should not be negative". Also, if both and are zero, then the method
must throw an exception which says "n and p should not be zero."For example, -4 and -5 would
result in java.lang.Exception: n or p should not be negative.Complete the function power in class
MyCalculator and return the appropriate result after the power operation or an appropriate
exception as detailed above.

import java.util.Scanner;
class MyCalculator {

public static int power(int n, int p) throws Exception{


if(n < 0 || p < 0){
throw new Exception ("n or p should not be negative.");
}else if(n==0 && p ==0){
throw new Exception("n and p should not be zero.");
}

else {
return ((int)Math.pow(n,p));
}
}
}

public class Solution {


public static final MyCalculator my_calculator = new MyCalcul
ator();
public static final Scanner in = new Scanner(System.in);

public static void main(String[] args) {


while (in .hasNextInt()) {
int n = in .nextInt();
int p = in .nextInt();

try {
System.out.println(my_calculator.power(n, p));
} catch (Exception e) {
System.out.println(e);
}
}
}
}
Input

35

24

00

-1 -2

-1 3

Output

243

16

java.lang.Exception: n and p should not be zero.

java.lang.Exception: n or p should not be negative.

java.lang.Exception: n or p should
4.Create a User-defined Exception which must throw when the student B.Tech marks below 60% and
Company written test marks below 70% marks during the company recruitment process.

class RecruitmentException extends Exception {

public RecruitmentException(String message) {

super(message);

class CompanyRecruitmentProcess {

public void conductRecruitment(int bTechMarks, int writtenTestMarks) throws


RecruitmentException {

if (bTechMarks < 60 || writtenTestMarks < 70) {

throw new RecruitmentException("B.Tech marks below 60% or written test marks below
70%");

} else {

System.out.println("Congratulations! You have cleared the recruitment process.");

public class Main {

public static void main(String[] args) {

CompanyRecruitmentProcess recruitmentProcess = new CompanyRecruitmentProcess();

// Example usage

try {

// Simulating student's B.Tech marks and company written test marks

int bTechMarks = 55;

int writtenTestMarks = 75;

recruitmentProcess.conductRecruitment(bTechMarks, writtenTestMarks);
} catch (RecruitmentException e) {

System.out.println("RecruitmentException: " + e.getMessage());

Input

B.Tech Marks: 55

Written Test Marks: 75

Output

RecruitmentException: B.Tech marks below 60% or written test marks below 70%
5.Create a user defined Exception which must be throw when the given phone number of the
student contains alphabets or symbols and the number of digits not equal to 10.

class InvalidPhoneNumberException extends Exception {

public InvalidPhoneNumberException(String message) {

super(message);

class Student {

private String phoneNumber;

public void setPhoneNumber(String phoneNumber) throws InvalidPhoneNumberException {

// Check if phone number contains alphabets or symbols

if (!phoneNumber.matches("\\d{10}")) {

throw new InvalidPhoneNumberException("Invalid phone number. Phone number must


contain 10 digits only.");

this.phoneNumber = phoneNumber;

public String getPhoneNumber() {

return phoneNumber;

public class Main {

public static void main(String[] args) {

Student student = new Student();

try {

// Set an invalid phone number

student.setPhoneNumber("123456789A");

} catch (InvalidPhoneNumberException e) {
System.out.println("InvalidPhoneNumberException: " + e.getMessage());

Input

123456789A

Output

InvalidPhoneNumberException: Invalid phone number. Phone number must contain 10 digits only.
6.Create Student class with ID, name, gender, and branch. Use getter and setters. The ID must be 9-
digit number, name must not have special characters and digits, gender must be either M/F and
branch must be either ECE/CSE/ME/ECSE/CE/BT/EEE. Use toString () to format the details of Student.
Create user defined exceptions for checking validity of the data. If data is not valid throw an
appropriate user defined exception from setter methods.

class InvalidDataException extends Exception {

public InvalidDataException(String message) {

super(message);

class Student {

private long id;

private String name;

private char gender;

private String branch;

// Constructor

public Student() {

// Getter and setter for ID

public long getId() {

return id;

public void setId(long id) throws InvalidDataException {

if (String.valueOf(id).length() != 9) {

throw new InvalidDataException("Invalid ID. ID must be a 9-digit number.");

this.id = id;
}

// Getter and setter for name

public String getName() {

return name;

public void setName(String name) throws InvalidDataException {

if (!name.matches("[a-zA-Z ]+")) {

throw new InvalidDataException("Invalid name. Name must not contain special characters or
digits.");

this.name = name;

// Getter and setter for gender

public char getGender() {

return gender;

public void setGender(char gender) throws InvalidDataException {

if (gender != 'M' && gender != 'F') {

throw new InvalidDataException("Invalid gender. Gender must be either 'M' or 'F'.");

this.gender = gender;

// Getter and setter for branch

public String getBranch() {

return branch;

}
public void setBranch(String branch) throws InvalidDataException {

if (!branch.matches("ECE|CSE|ME|ECSE|CE|BT|EEE")) {

throw new InvalidDataException("Invalid branch. Branch must be one of ECE, CSE, ME, ECSE,
CE, BT, or EEE.");

this.branch = branch;

// toString() method to format the details of Student

@Override

public String toString() {

return "Student ID: " + id + "\nName: " + name + "\nGender: " + gender + "\nBranch: " + branch;

public class Main {

public static void main(String[] args) {

// Example usage

Student student = new Student();

try {

student.setId(123456789); // Set valid ID

student.setName("John Doe"); // Set valid name

student.setGender('M'); // Set valid gender

student.setBranch("CSE"); // Set valid branch

System.out.println(student.toString()); // Print student details

} catch (InvalidDataException e) {

System.out.println("InvalidDataException: " + e.getMessage());

}
}

Input

ID: 123456789

Name: John Doe

Gender: M

Branch: CSE

Output

Student ID: 123456789

Name: John Doe

Gender: M

Branch: CSE

You might also like