About the enabling and disabling of assertion statements in java in eclipse

     When learning java exception handling for the first time, you will definitely use throws and throw statements to throw exceptions and handle exceptions. At the same time, you will also learn a keyword assert error and assertion statement. However, when testing the assert statement in eclipse, it will be found that the assert statement does not work, as in the following example:

import java.util.*;
public class ex9 {
	public static void main(String[]args)
	{
		Scanner scan=new Scanner(System.in);
		while(scan.hasNext())
		{
	   System.out.println("请输入要计算平方根的数:");
	   int x=scan.nextInt();
	   assert x>0:"负数不能求平方根";
	   double y=Math.sqrt(x);
	   System.out.println(x+"的平方根的数为:"+y);
		}
		scan.close();
			   
    }
}

operation result:

According to the running results, it can be seen that the program does not exit when the input value is less than or equal to 0, that is, the assertion statement is invalid.

This is because assertions are suitable for use in the debugging process. Although java has introduced assertions since 1.4, the default assertion function is not enabled .

Solution:

Select the menu: Run ---> Run Configurations...---> select the Arguments tab

Enter: -ea in the VM arguments text box, save and run again .

operation result


It is recommended that after testing the assert assertion statement, open the VM arguments text box again and enter -da to disable the assertion.

Guess you like

Origin blog.csdn.net/M_TDM/article/details/79923208