I am a java student and I am writing a java program with exception handling. In this program, I am trying to write a program that gets 5 even number from user and if the user enter odd number then show an exception that the number is odd. I am using custom exception "oddexception" in this program.
Now let's talk about the issue. So I have an issue that this program isn't compiling. It show an error which is mentioned in the image below.
The answer to this question can be small and stupid for you but I am a beginner in java so this answer really matters for me. please help me.
Please help me to find a solution. The solution
import java.lang.Exception;
class oddexception extends Exception
{
oddexception(String message, int a)
{
System.out.println(message);
System.out.println("Invalid Number is/are "+a);
}
}
class program4
{
public static void main(String args[])
{
Integer n[] = new Integer[5];
int j=0;
for(int i=0; i<5; i++)
{
try
{
n[i] = Integer.valueOf(args[i]);
if(n[i]%2!=0)
{
j++;
throw new oddexception("Number is odd "+n[i]);
}
}
catch(oddexception e)
{
System.out.println("Caught my exception");
}
}
System.out.println("Invalid numbers are : "+j);
}
}

From the error message it quite clear that the constructor of your exception is expecting a String and an integer (oddexception(String message, int a)). Where as you just passing a String.
throw new oddexception("Number is odd "+n[i]); //results to String
So changing a bit of your code
throw new oddexception("Number is odd " , n[i]);
Your oddexception constructor has two arguments, so instead of
throw new oddexception("Number is odd "+n[i]);
you should write
throw new oddexception("Number is odd ",n[i]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With