The difference between throws and throw

throw: is used in the code block, mainly to manually throw exception objects

throws: Used on the method definition, it means that a generated one in this method is clearly told to the caller

package day10_Exception;
/**
 * throws 使用
 * @author  tao
 *
 */
class Try{
	public static int div(int x,int y) {
		return x/y;
	}
}
public class java_Exception {
public static void main(String[] args) {
	
	try {
		throw new Exception();
		
	} catch (Exception e) {
		
		e.printStackTrace();
	}
	
}
}

 

package day10_Exception;
/**
 * throws 使用
 * @author tao
 *
 */
class Try{
	public static int div(int x,int y) throws Exception {
		return x/y;
	}
}
public class java_Exception {
public static void main(String[] args) {
	try {    //必须声明try-catch
	System.out.println(Try.div(4, 3));
	}catch(Exception e) {
		e.printStackTrace();
	}
}
}

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_41663470/article/details/113435475