Suppose that statement2 causes an exception in the following statement.
Suppose that statement2 causes an exception in the following statement:
try {
statement1;
statement2;
statement3;
}
Catch (Exception ex1)
{
}
catch (Exception2 ex2)
{
throw ex2;
}
catch (Exception3 ex3)
{
}
finally {
statement4;
}
statement5;
What you predicts the behavior of the code if catch (Exception e) is added at line 18. Give proper demonstration of it in Intellij Idea Output of Whole screen and statement2 causes an exception
In subtraction if the value of second number is greater than first number method throws IllegalArgumentException and print message “answer is negative”. Create main class that display one normal execution of subtraction and one with exception case
Summary
In the below code we are supposed to subtract two numbers and only a positive answer is excepted. If it shows us the negative output, we will have to throw an exception, in such case we have IllegalArgumentException in java. We know there are different types of exceptions in java. But here we will only use IllegalArgumentException and ArithmeticException. So if we want to throw an exception we have to use try and catch block.
Explanation
In the below code, we have started with a Class name i.e. Argument followed by the main method. Then we opened the try block where we have declared three variables and two of them have assigned a value. The name of the three variables are ‘first_no’ with a value of 05, and ‘second_no’ with a value of 10, and our third variable that we are going to use for storing the output of subtraction is ‘result’.
As we are going to subtract the first number from the second, it will check the output. If the output is positive then there is no problem but if we have a negative output at that time the IllegalArithmaticException is thrown. Once the exception is thrown the remaining part of the try block will not get executed. Once the exception part is done finally part of the code will get executed i.e. ‘completed successfully’.
Code
class Argument
{
public static void main(String a[])
{
try
{
//First Statement
int first_no=05;
//Second Statement
int second_no=10;
//Third Statement
int result=first_no-second_no;
if(result<0)
{
throw new IllegalArgumentException("Negative result");
}
}
catch(ArithmeticException ae1)
{
}
catch(Exception ae2)
{
throw ae2;
}
finally
{
System.out.println("Excutes");
}
System.out.println("Completed");
}
}
Output