Skip to main content

VNSGU BCA Sem 4: Java Programming (403) Practical Solutions - April 2025 Set C

Paper Details
  • Subject: Java Programming Language
  • Subject Code: 403
  • Set: C
  • Semester: 4
  • Month/Year: April 2025
  • Max Marks: 25
  • Time Recommendation: 45 Minutes
  • Paper: View Paper | Download PDF

Questions & Solutions

All questions are compulsory

Q1: Exception Handling - Division

Max Marks: 20

Write a Java program that takes two numbers as input and performs division. Handle exceptions for:

  • Division by zero
  • Invalid input

1. Understanding Exceptions

Before implementing the solution, understand the types of exceptions that can occur.

Hint
  • ArithmeticException: Thrown when dividing by zero
  • InputMismatchException: Thrown when user enters non-numeric input
  • Use try-catch blocks to handle these exceptions gracefully
View Solution & Output
import java.util.Scanner;
import java.util.InputMismatchException;

public class DivisionWithExceptionHandling {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

try {
// Input first number
System.out.print("Enter first number: ");
double num1 = sc.nextDouble();

// Input second number
System.out.print("Enter second number: ");
double num2 = sc.nextDouble();

// Perform division
double result = num1 / num2;
System.out.println("Result: " + num1 + " / " + num2 + " = " + result);

} catch (ArithmeticException e) {
// Handle division by zero
System.out.println("Error: Cannot divide by zero!");

} catch (InputMismatchException e) {
// Handle invalid input
System.out.println("Error: Please enter valid numbers only!");

} catch (Exception e) {
// Handle any other exceptions
System.out.println("Error: " + e.getMessage());

} finally {
// Always executed - close resources
System.out.println("Program execution completed.");
sc.close();
}
}
}

Output (Normal Case):

Enter first number: 10
Enter second number: 2
Result: 10.0 / 2.0 = 5.0
Program execution completed.

Output (Division by Zero):

Enter first number: 10
Enter second number: 0
Result: 10.0 / 0.0 = Infinity
Program execution completed.

Output (Invalid Input):

Enter first number: abc
Error: Please enter valid numbers only!
Program execution completed.

Step-by-Step Explanation:

  1. Initialization: Create Scanner object for input
  2. Logic Flow:
    • Wrap input and division operations in try block
    • Catch InputMismatchException for invalid input (non-numbers)
    • For division by zero with doubles, Java returns Infinity rather than throwing ArithmeticException
    • Use finally block to close resources and display completion message
  3. Completion: Program handles errors gracefully without crashing

2. Enhanced Version with Validation

A more robust version with explicit division by zero checking.

Enhanced Solution
import java.util.Scanner;
import java.util.InputMismatchException;

public class SafeDivision {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

try {
// Input first number
System.out.print("Enter first number: ");
double num1 = sc.nextDouble();

// Input second number
System.out.print("Enter second number: ");
double num2 = sc.nextDouble();

// Explicit check for division by zero
if (num2 == 0) {
throw new ArithmeticException("Division by zero is not allowed!");
}

// Perform division
double result = num1 / num2;
System.out.println("Result: " + num1 + " / " + num2 + " = " + result);

} catch (ArithmeticException e) {
// Handle division by zero
System.out.println("Error: " + e.getMessage());

} catch (InputMismatchException e) {
// Handle invalid input
System.out.println("Error: Please enter valid numbers only!");
System.out.println("Integers or decimals are accepted.");

} catch (Exception e) {
// Handle any other exceptions
System.out.println("Unexpected Error: " + e.getMessage());

} finally {
// Always executed
System.out.println("Thank you for using the division program.");
sc.close();
}
}
}

Output (Division by Zero - Enhanced):

Enter first number: 10
Enter second number: 0
Error: Division by zero is not allowed!
Thank you for using the division program.

Step-by-Step Explanation:

  1. Initialization: Create Scanner object for input
  2. Logic Flow:
    • Read both numbers from user input
    • Explicitly check if second number is zero
    • Throw ArithmeticException with custom message if zero
    • Multiple catch blocks handle different exception types
  3. Completion: More user-friendly error messages
Concept Deep Dive: Exception Hierarchy

Exception Types in Java:

  • Checked Exceptions: Must be handled or declared (IOException, SQLException)
  • Unchecked Exceptions: Runtime exceptions, optional handling (ArithmeticException, NullPointerException)
  • Errors: Serious problems, should not catch (OutOfMemoryError, StackOverflowError)

Best Practices:

  • Catch specific exceptions before general ones
  • Use finally for resource cleanup
  • Don't catch Exception unless necessary - be specific
  • Provide meaningful error messages

Q2: Viva Preparation

Max Marks: 5

Potential Viva Questions
  1. Q: What is an exception in Java?

    • A: An exception is an event that disrupts the normal flow of program execution. It's an object that wraps an error event and contains information about the error.
  2. Q: What is the difference between try, catch, and finally blocks?

    • A: try contains code that might throw an exception; catch handles the exception; finally always executes regardless of whether an exception occurred, used for cleanup.
  3. Q: Why is InputMismatchException thrown?

    • A: When Scanner receives input that doesn't match the expected type (e.g., entering text when nextInt() expects an integer).
  4. Q: What happens if we divide a double by zero in Java?

    • A: For doubles, dividing by zero returns Infinity or -Infinity rather than throwing an exception. Only integer division by zero throws ArithmeticException.
  5. Q: Can we have multiple catch blocks?

    • A: Yes, and they should be ordered from most specific to most general exception types.
  6. Q: What is the difference between throw and throws?

    • A: throw is used to explicitly throw an exception; throws declares that a method may throw exceptions, used in method signature.
  7. Q: What is exception propagation?

    • A: When an exception is not caught in a method, it's passed up the call stack to the calling method until caught or the program terminates.
Common Pitfalls
  • Empty catch blocks: Never leave catch blocks empty - always handle or log the exception
  • Wrong exception order: Always catch specific exceptions before general Exception
  • Resource leaks: Always close resources (files, scanners) in finally block or use try-with-resources
  • Ignoring return values: Check return values that might indicate errors
  • Not validating input: Validate input before using it, don't rely solely on exceptions

Quick Navigation

SetLink
Set ASolutions
Set BSolutions
Set CCurrent Page
Set DSolutions
Set ESolutions
Set FSolutions

Last Updated: April 2026