throw 和 throws 的区别?
1、throw:指的是语句抛出一个异常。
例如:如下写了一个抛出异常的语句。利用throw可以自定义异常。
private void checkIndex(int index) {
if (index <= size - 1 && index >= 0) {
} else {
throw new IndexOutOfBoundsException("index:" + index + " size:"
+ size);
}
}
2、throws:指的是方法可能会抛出的异常的声明。
例如:下面的代码可能会抛出IO异常。
/**
* 文件拷贝
*
* @param fromPath
* @param toPath
* @throws IOException
*/
public static void fileCopy(String from, String to) throws IOException {
// 1、建立联系 file对象。源:存在且为文件+目的地:文件可以不存在
File fromPath = new File(from);
File toPath = new File(to);
fileCopy(fromPath, toPath);
}