icenine icenine - 1 year ago 65
Java Question

Exceptions in Java - Try/ Catch

I'm learning Java and I have this program that tells the sign depending on the day and month the user writes. The program works as it is, but if the user enters a day like 90 or so, the program doesnt evaluate that "error". Can I correct this with a try/catch? If so, how do I write it? Here's the code (a piece of it), thanks in advance

import java.util.Scanner;
public class Signo{
public static void main(String[] args) {

Scanner in = new Scanner(;

int day, month;

System.out.println("Day Input:");


System.out.println("Month Input:");


int result=getSign(day,month);


private static int getSign(int day, int month){

case 1:
if(month==1 && day>=20){
System.out.println("Your sign is Aquarius");
System.out.println("Your sign is Capricorn");
return day;

Answer Source

It's pretty simple, really...

     //statements that may cause an exception
catch (exception(type) e(object))‏
     //error handling code

That's all you really need right there. Just put your code that you think might break in the appropriate spot.

Though, having read the comment, I agree that this is overkill for what you're doing.

You just need to set a condition for a While loop:

boolean goodAnswer = false;

while goodAnswer == false{
   System.out.println("Day Input:");

  if (day<31) { goodAnswer=true; }

A routine like this will effectively keep on asking for an integer until it gets one it likes. Only then will it leave the loop. This is a fairly common approach for this sort of thing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download