11.5throws keyword

During program execution calls often involve different types of methods, but for the convenience of callers to handle exceptions, these methods often in a statement to mark anomalies that may arise, then you need to realize throws keyword
examples : use the keyword throws observed

public class MyMath {
        /**
         * 除法可能出现异常
         */
	public static int div(int x,int y) throws Exception {
		return x/y;
	}
}

public class Java249 {
       public static void main(String[] args) {
		try {
			System.out.println(MyMath.div(10, 2));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Execution result
. 5
this procedure call in the main category MyMath.div () method implements the division operation, since the use of this method throws an exception is thrown, so that when this method is invoked must explicitly use the exception handling process statement statement may abnormal occurrence

The method itself is the main part of a method in java, so the main method throws thrown if used, they can not represent mandatory exception handling inside the main method. If an exception occurs, will be handed over to the JVM default processing will cause the program to break execution. Therefore, in the actual development, the main program is often used as a starting point the existence of the program, all the exceptions should be completed in its entirety in the main method should not throw up.

Published 162 original articles · won praise 9 · views 3083

Guess you like

Origin blog.csdn.net/ll_j_21/article/details/104733985