Exception Handling and Assertions: past questions

19 questions · 97 marks · 8 papers. Try each one before checking.

Solve them and check answers →Read the notes first

2023 Aug

Question 5 MCQ · 3 marks

Consider the Java code given below.

class Arithmetic{
    public static void div(int a, int b) throws Exception {
        System.out.println(a/b);
    }
    public static void getResult() throws Exception {
        try {
            div(10, 0);
            div(12, 6);
        } catch(Exception e) {
            System.out.println("caught in getResult");
            throw e;
        }
    }
}
public class ExceptionTest {
    public static void main(String[] args) throws Throwable {
        try {
            Arithmetic.getResult();
        } catch(Exception e) {
            System.out.println("caught in main");
        }
    }
}

Choose the correct option.

  1. This program generates the output:

    caught in main
    caught in getResult
  2. This program generates the output:

    caught in getResult
    caught in main
    2
  3. This program generates the output:

    caught in getResult
    2
    caught in main
  4. This program terminates abnormally due to unhandled exceptions.

  5. This program generates the output:

    caught in getResult
    caught in main

Question 6 MCQ · 3 marks

Consider the Java code given below.

class SelectionException extends Exception{
    public SelectionException(String str){
        super(str);
    }
}
class Player{
    private String name;
    private int runs;
    private double strikerate;
    //Constructor to initialize name, runs and strikerate
    public void selection() throws SelectionException{
        System.out.println("Hello " + this.name);
        if(this.runs > 300){
            if(this.strikerate > 150){
                System.out.println("You have selected in to the team");
            }
            else {
                throw new SelectionException("You have less strike rate");
            }
        }
        else {
            throw new SelectionException("You have scored less runs");
        }
    }
}
public class UserExceptionTest {
    public static void main(String[] args) {
        Player p1 = new Player("Dhoni", 340, 98.9);
        Player p2 = new Player("Russel", 295, 100.8);
        try {
            p1.selection();
            p2.selection();
        }
        catch(SelectionException e){
            System.out.println(e.getMessage());
        }
    }
}

What will the output be?

  1. Hello Dhoni
    You have less strike rate
  2. Hello Russel
    You have less strike rate
    You have scored less runs
  3. Hello Dhoni
    You have less strike rate
    Hello Russel
    You have less strike rate
    You have scored less runs
  4. Hello Dhoni
    You have less strike rate
    Hello Russel
    You have scored less runs

Question 8 MCQ · 3 marks

Consider the Java code given below.

class UPIUser{
    private String name, phone;
    public UPIUser(String n, String p) {
        this.name = n;
        this.phone = p;
    }
    public String getUpiID() {
        assert name != null : "Invalid name"; //LINE 1
        assert phone.length() == 10 : "Should be 10 digits" ; //LINE 2
        assert phone != null : "Invalid phone number" ; //LINE 3
        return phone + "@ybl";
    }
}
public class AssertionTest {
    public static void main(String[] args) {
        UPIUser u1 = new UPIUser("", "730007311");
        UPIUser u2 = new UPIUser("Sudarshan", null);
        System.out.println(u1.getUpiID()); // LINE 4
        System.out.println(u2.getUpiID()); // LINE 5
    }
}

Choose the correct option when the program is executed as: java -ea AssertionTest

  1. LINE 1 throws AssertionError when LINE 4 is executed.

  2. LINE 2 throws AssertionError when LINE 4 is executed.

  3. LINE 2 throws AssertionError when LINE 5 is executed.

  4. LINE 3 throws AssertionError when LINE 5 is executed.

2023 Dec

Question 7 MCQ · 3 marks

Consider the Java code given below.

class MinScoreException extends Exception{
    public MinScoreException() {
        super("application rejected: low score");
    }
}
class Application{
    private int score;
    public Application(int s){
        score = s;
    }
    public void validate() throws MinScoreException{
        if (score < 75)
            throw new MinScoreException();
        System.out.println("applied successfully");
    }
}
class Test{
    public static void main(String[] args) {
        Application ap1 = new Application(65);
        Application ap2 = new Application(90);
        try {
            ap1.validate();
            ap2.validate();
        }
        catch(Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

Choose the correct option.

  1. This program generates output:

    application rejected: low score
  2. This program generates output:

    application rejected: low score
    applied successfully
  3. This program generates output:

    application rejected: low score
    applied successfully
    applied successfully
  4. The program crashes due to the uncaught exception: MinScoreException

Question 6 MCQ · 3 marks

Consider the Java code given below.

class Validation {
    public boolean validate(int a, int b) {
        assert a > 0 : "a should be positive"; //LINE 1
        assert b > 0 : "b should be positive"; //LINE 2
        return true;
    }
}
public class AssertTest {
    public static void main(String[] args) {
        int a = -10;
        int b = -5;
        int result = 0;
        assert a != 0 : a; //LINE 3
        assert b != 0 : b; //LINE 4
        Validation obj = new Validation();
        if (obj.validate(a, b))
            result = a / b;
        assert result > 0 : result; //LINE 5
        System.out.println(result);
    }
}

Identify the line that throws AssertionError when the program is executed as: java -ea AssertTest

  1. LINE 1

  2. LINE 2

  3. LINE 3

  4. LINE 4

  5. LINE 5

2024 Mar 24

Question 12 MCQ · 7 marks

Consider the Java code given below.

class MinimumMarksException extends Exception {
    public MinimumMarksException(String message) {
        super(message);
    }
}
class Student {
    private double marks;
    private final double MINIMUM_MARKS = 40.0;
    // Constructor to initialize the marks
    public void checkResult() throws MinimumMarksException {
        if (marks < MINIMUM_MARKS) {
            throw new MinimumMarksException("Minimum marks not scored");
        } else {
            System.out.println("Scored sufficient marks");
        }
    }
}
public class Test {
    public static void main(String[] args) {
        Student s1 = new Student(55.0);
        Student s2 = new Student(30.0);
        try {
            s1.checkResult();
            s2.checkResult();
        } catch (MinimumMarksException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Choose the correct option.

  1. This program generates the output:

    Scored sufficient marks
    Error: Minimum marks not scored
  2. This program generates the output:

    Scored sufficient marks
    MinimumMarksException
  3. This program generates the output:

    Scored sufficient marks
    Minimum marks not scored
  4. This program generates the output:

    Error: MinimumMarksException

Question 4 MCQ · 6 marks

Consider the Java code given below.

class Validation {
    public boolean validate(int a, int b) {
        assert a > 0 : "a should be greater than zero";    //LINE 1
        assert b >= 1 : "b should not be less than one";   //LINE 2
        return true;
    }
}
public class AssertTest {
    public static void main(String[] args) {
        int a = 1;
        int b = -1;
        int result = 0;
        Validation obj = new Validation();
        if (obj.validate(a, b))
            result = a / b;
        assert result > 0 : "result should be greater than zero"; //LINE 3
        System.out.println(result);
    }
}

Choose the correct option when the program is executed as: java -ea AssertTest

  1. LINE 1 generates assertion error.

  2. LINE 2 generates assertion error.

  3. LINE 3 generates assertion error.

  4. This program does not generate assertion error.

2024 Aug 04

Question 11 MCQ · 7 marks

Consider the Java code given below.

class InvalidTemperatureException extends RuntimeException {
    public InvalidTemperatureException(String message) {
        super(message);
    }
}
class Thermostat {
    private double temperature;
    private final double MIN = 0.0;
    private final double MAX = 35.0;
    public Thermostat(double t) {
        if (t < MIN || t > MAX) {
            throw new InvalidTemperatureException("Temperature out of operating range");
        }
        this.temperature = t;
    }
}
public class ClimateControl {
    public static void main(String[] args) {
        try {
            Thermostat t1 = new Thermostat(22.0);
            Thermostat t2 = new Thermostat(36.0);
        } catch (InvalidTemperatureException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Choose the correct option.

  1. This program runs without any exception.

  2. This program generates the output: Error: Temperature out of operating range

  3. This program compiles successfully but generates no output.

  4. This program generates the output: Error: InvalidTemperatureException

Question 4 MCQ · 6 marks

Consider the Java code given below.

class NewUser{
    private String name, password;
    public NewUser(String s, String p) {
        this.name = s;
        this.password = p;
    }
    public String getUserName() {
        assert name != null : "Invalid name"; //LINE 1
        assert password.length() == 10 : "Should be 10 characters"; //LINE 2
        return name + "@acct.com";
    }
}
public class Test {
    public static void main(String[] args) {
        NewUser u1 = new NewUser("", "password");
        NewUser u2 = new NewUser("Sudarshan", "1234567890");
        String username1 = u1.getUserName(); //LINE 3
        assert username1 != null : "Should not be null"; // LINE 4
        String username2 = u2.getUserName(); //LINE 5
        assert username2 != null : "Should not be null"; // LINE 6
        System.out.println(username1);
        System.out.println(username2);
    }
}

Choose the correct option when the program is executed as: java -ea Test

  1. LINE 1 throws AssertionError.

  2. LINE 2 throws AssertionError.

  3. LINE 4 throws AssertionError

  4. LINE 6 throws AssertionError

2025 Mar 16

Question 7 MCQ · 6 marks

Consider the following Java code.

class SalaryProcessor {
    public static void calSalary(int bs, int bonus) throws Exception {
        if (bonus < 0) {
            throw new Exception("Invalid bonus");
        }
        System.out.println("Total Salary: " + (bs + bonus));
    }
    public static void processSalaries() throws Exception {
        try {
            calSalary(50000, 10000);
            calSalary(60000, -5000);
        } catch (Exception e) {
            System.out.println("Caught in processSalaries");
            throw e;
        }
    }
}
public class Test {
    public static void main(String[] args) throws Throwable {
        try {
            SalaryProcessor.processSalaries();
        } catch (Exception e) {
            System.out.println("Caught in main");
        }
    }
}

Choose the correct option.

  1. This program generates the output:

    Caught in processSalaries
    Caught in main
  2. This program terminates abnormally due to unhandled exceptions.

  3. This program generates the output:

    Total Salary: 60000
    Caught in processSalaries
    Caught in main
  4. This program generates the output:

    Total Salary: 60000
    Caught in main
    Caught in processSalaries

Question 8 MCQ · 7 marks

Consider the Java code given below.

class RegException extends Exception {
    public RegException(String message) {
        super(message);
    }
}
class User {
    private String email;
    public User(String e) {
        email = e;
    }
    public void register() throws RegException {
        if (!email.contains("@")) {
            throw new RegException("Registration failed: Invalid email format");
        }
        System.out.println("Registration successful");
    }
}
public class Test {
    public static void main(String[] args) {
        User u1 = new User("anu.kuriyan@ex.com");
        User u2 = new User("narendran.pk");
        try {
            u1.register();
            u2.register();
        } catch (RegException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Choose the correct option.

  1. This program generates the output:

    Registration successful
    Error: Registration failed: Invalid email format
  2. This program generates the output:

    Registration successful
    RegException
  3. This program generates the output:

    Registration successful
    Registration failed: Invalid email format
  4. This program generates the output:

    Error: Registration failed: Invalid email format

Question 10 MCQ · 7 marks

Consider the Java code given below.

public class AssertTest{
    public static double caltempDiff(double currentTemp, double idealTemp) {
        double tempdiff = 0;
        assert currentTemp >= -100 && currentTemp <= 150; // assert-1
        assert idealTemp >= -100 && idealTemp <= 150;     // assert-2
        tempdiff = currentTemp - idealTemp;
        assert tempdiff >= 0;                             // assert-3
        return tempdiff;
    }
    public static void main(String[] args) {
        double currentTemp = 35.0;
        double idealTemp = 37.0;
        assert currentTemp >= -100 && currentTemp <= 150; // assert-4
        double tempDifference = caltempDiff(currentTemp, idealTemp);
    }
}

Identify the first assert statement that throws the AssertionError when the class is executed as: java -ea AssertTest

  1. assert-1

  2. assert-2

  3. assert-3

  4. assert-4

2026 Apr 06

Question 13 MCQ · 7 marks

Consider the following Java code that uses chained exceptions in the context of a sports match analysis system.

class MatchDataException extends Exception {
    public MatchDataException(String message) {
        super(message);
    }
}
class PerformanceAnalysisException extends Exception {
    public PerformanceAnalysisException(String message) {
        super(message);
    }
}
class SportsAnalyzer {
    public void analyzeMatch(String team) throws PerformanceAnalysisException {
        try {
            if (team == null || team.isEmpty()) {
                throw new MatchDataException("Corrupted match data");
            } else {
                // actual performance analysis logic
                System.out.println("Analyzing performance for " + team);
            }
        } catch (MatchDataException e) {
            PerformanceAnalysisException pae =
                new PerformanceAnalysisException("Analysis failed");
            pae.initCause(e);
            throw pae;
        }
    }
}
public class MatchApp {
    public static void main(String[] args) {
        SportsAnalyzer analyzer = new SportsAnalyzer();
        try {
            analyzer.analyzeMatch("Team Tigers");
            analyzer.analyzeMatch("");
        } catch (PerformanceAnalysisException e) {
            System.out.println(e.getMessage());
            System.out.println("Reason: " + e.getCause().getMessage());
        }
    }
}

What can the output of this code be?

  1. Analyzing performance for Team Tigers
    Analysis failed
    Reason: Corrupted match data
  2. Corrupted match data
    Reason: Analysis failed
  3. Reason: Corrupted match data
  4. Analysis failed
    Reason: Corrupted match data

Question 9 MCQ · 7 marks

Consider the following Java code.

class Telescope {
    private double maxZoom, currentZoom, aperture;
    public Telescope(double m, double c, double a) {
        assert a > 0 : "Aperture must be positive";
        maxZoom = m;
        currentZoom = c;
        aperture = a;
    }

    public double adjustZoom(double amount) {
        assert amount > 0 : "Zoom increment must be positive";
        assert currentZoom + amount <= maxZoom : "Zoom exceeds telescope limit";
        currentZoom += amount;
        return currentZoom;
    }
}

class TelescopeTest {
    public static void main(String[] args) {
        Telescope t = new Telescope(1000.0, 800.0, 150.0);
        System.out.println(t.adjustZoom(300.0));
    }
}

Choose the correct option when the class is executed as: java -ea TelescopeTest

  1. This code generates output: 1100.0

  2. This code generates AssertionError: Zoom increment must be positive

  3. This code generates AssertionError: Zoom exceeds telescope limit

  4. This code generates AssertionError: Aperture must be positive

2025 Aug 03

Question 10 MCQ · 7 marks

Consider the Java code given below.

class LogFailureException extends Exception {
    public LogFailureException(String message) {
        super(message);
    }
}
class Logger {
    public void logEvent(String content) throws LogFailureException {
        //check whether content == null or content == ""
        if (content == null || content.isEmpty()) {
            throw new LogFailureException("Log content is empty");
        }
        System.out.println("LOG: " + content);
    }
}
class AuthService {
    private Logger logger = new Logger();
    public void authenticate(String username, String password)
            throws LogFailureException {
        if (username.equals("admin") && password.equals("admin123")) {
            logger.logEvent("User " + username + " authenticated.");
        } else {
            logger.logEvent("");
        }
    }
}
public class TestUser {
    public static void main(String[] args) {
        AuthService auth = new AuthService();
        try {
            auth.authenticate("guest", "12345");
            auth.authenticate("admin", "admin123");
        } catch (LogFailureException e) {
            System.out.println("Exception: " + e.getMessage());
        }
    }
}

Choose the correct option.

  1. This program generates the output:

    LOG: User admin authenticated.
  2. This program generates the output:

    Exception: Log content is empty
  3. This program generates the output:

    Exception: Log content is empty
    LOG: User admin authenticated.
  4. This program generates the output:

    LOG: User guest authenticated.
    LOG: User admin authenticated.

Question 4 MCQ · 6 marks

Consider the following Java code.

class User {
    private String username;
    private String password;
    public User(String u, String p) {
        assert u != null;            // assert-1
        assert p != null;            // assert-2
        username = u;
        password = p;
    }
    public boolean login() {
        assert !username.isEmpty();  // assert-3
        assert password.length() >= 6; // assert-4
        return username.equals("admin") && password.equals("admin123");
    }
}
public class AssertTest {
    public static void main(String[] args) {
        User user = new User("admin", "");
        System.out.println("Login status: " + user.login());
    }
}

Identify the first assert statement that throws the AssertionError when the class is executed as: java -ea AssertTest

  1. assert-1

  2. assert-2

  3. assert-3

  4. assert-4

2022 July

Question 11 MCQ · 3 marks

Consider the Java code given below.

class Test{
    public static void method1() throws Exception {
        System.out.println(10/0);
    }
    public static void method2() throws Throwable {
        try {
            method1();
        }
        catch(Exception e) {
            System.out.println("caught in method2()");
            throw e;
        }
    }
}
public class Example {
    public static void main(String[] args) throws Throwable {
        try {
            Test.method2();
        }
        catch(Exception e) {
            System.out.println("caught in main");
        }
    }
}

Choose the correct option.

  1. This program generates the output:

    caught in main
    caught in method2()
  2. This program generates the output:

    caught in method2()
  3. This program generates the output:

    caught in method2()
    caught in main
  4. This program terminates abnormally due to unhandled exceptions.

Question 8 MCQ · 3 marks

Consider the Java code given below.

class InvalidIndexException extends Exception{
    public InvalidIndexException() {
        super("invalid exception");
    }
}
public class Main {
    public static void getSubString(String a, int s, int e)
                                   throws StringIndexOutOfBoundsException {
        try {
            if(s > e)
                throw new InvalidIndexException();
            else
                System.out.println(a.substring(s, e));
        }
        catch(InvalidIndexException ie) {
            StringIndexOutOfBoundsException ne;
            ne = new StringIndexOutOfBoundsException("string index out of bound");
            ne.initCause(ie);
            throw ne;
        }
    }
    public static void main(String[] args) {
        try {
            getSubString("Java program", 5, 0);
        }
        catch(StringIndexOutOfBoundsException se) {
            System.out.println(se.getMessage());
            System.out.println(se.getCause().getMessage());
        }
    }
}

What will the output be?

  1. string index out of bound
    invalid exception
  2. invalid exception
    string index out of bound
  3. string index out of bound
    null
  4. string index out of bound
    string index out of bound

Question 9 MCQ · 3 marks

Consider the Java code given below.

class AssertPositive{
    public static boolean assertPos(int a){
        assert a > 0: "a should not be negative"; //LINE-1
        return true;
    }
}
class AssertNonZero{
    public static boolean assertNonZero(int b){
        assert b != 0: "b should not be zero";    //LINE-2
        return true;
    }
}
public class AssertionTest {
    public static void main(String[] args) {
        int a = -1;
        int b = 0;
        int result = 0;

        if (AssertPositive.assertPos(a) && AssertNonZero.assertNonZero(b))
            result = a - b;                       //LINE-3
        System.out.println(result);
    }
}

Choose the most appropriate option regarding the code when executed as: java -ea:AssertNonZero AssertionTest

  1. LINE-1 gives AssertionError

  2. LINE-2 gives AssertionError

  3. LINE-3 gives AssertionError

  4. This program generates the output: -1

Check your answers →

Weeks covering this topic

Other Java topics