throws和throw区别

throw:是在代码块中使用,主要的手工进行异常对象的抛出

throws:在方法定义上使用的,表示将此方法中产生的一次明确告诉给调用处

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();
	}
}
}

猜你喜欢

转载自blog.csdn.net/qq_41663470/article/details/113435475