How to get a specific type of exception in Java

Viewed 667

I am trying to get a specific exception

Input H=-1; B=2;

Expected Output

java.lang.Exception: Breadth and height must be positive

Current Output

-2

public class Solution {
static int H,B;
static boolean flag = true;
static                                         //static initializer block
{
    
    Scanner sc = new Scanner(System.in);
    H=sc.nextInt();
    B=sc.nextInt();
    
}

public static void main(String[] args){
        if(flag){
            int area=B*H;
            System.out.print(area);
        }
        
    }

}

How do I get that specific exception?

3 Answers

You can throw your own exception like this

if(H<0 || B<0){
 throw new Exception("Breadth and height must be positive");
}

However, it would be a better practice to use something like a IllegalArgumentException for this.

if(H<0 || B<0){
 throw new IllegalArgumentException("Breadth and height must be positive");
}

Add this as the first lines of your main method:

if(B < 1 || H < 1) {
    throw new Exception("Breadth and height must be positive");
}

Add a throw statement. You can add it into a try catch block or instead add throws Exception (or a more specific exception) to the method signature (the latter is shown below):

import java.util.Scanner;

public class Solution {
    static int H,B;
    static boolean flag = true;

    //static initializer block
    static {
        Scanner sc = new Scanner(System.in);
        H = sc.nextInt();
        B = sc.nextInt();
    }

    public static void main(String[] args) throws Exception {
        if (flag) {
            if (H < 0 || B < 0) {
                throw new Exception("Breadth and height must be positive");
            } else {
                int area = B * H;
                System.out.print(area);
            }
        }
    }
}

Or you could put the try block with throw statement in your static initializer block:

import java.util.Scanner;

public class Solution {
    static int H,B;
    static boolean flag = true;

    //static initializer block
    static {    
        Scanner sc = new Scanner(System.in);
        H = sc.nextInt();
        B = sc.nextInt();

        if (H < 0 || B < 0) {
            try {
                throw new Exception("Breadth and height must be positive");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        if (flag) {
            int area = B * H;
            System.out.print(area);
        }
    }
}
Related