我很确定这很容易,但我找不到直截了当的答案.如何调用方法throws FileNotFoundException?
这是我的方法:
private static void fallingBlocks() throws FileNotFoundException
Run Code Online (Sandbox Code Playgroud) 在以下示例中,Eclipse不要求我添加“ throws EmptyStackException”
public E pop() {
if (stack.isEmpty()) {
throw new EmptyStackException();
}
...
}
Run Code Online (Sandbox Code Playgroud)
但是,在以下示例中,“ throw Exception”是必需的
public E pop() throws Exception {
if(stack.isEmpty()) {
throw new Exception();
...
}
Run Code Online (Sandbox Code Playgroud)
关于何时应该添加引发的任何特定规则?
我有一个需要抛出异常的函数,但我希望它将该异常抛出到我调用该函数的行:
static int retrieveInt()
{
int a = getInt();
if(a == -1)
throw new Exception("Number not found"); //The runtime error is pointing to this line
return a;
}
static void Main(string[] args)
{
int a = retrieveInt(); //The runtime error would be happening here
}
Run Code Online (Sandbox Code Playgroud) 这里的“throws”关键字是什么意思:

这段代码需要很长时间才能执行,我认为上图中的“throws”关键字相关:
let url = URL(string:"\(APIs.postsImages)\(postImg)")
let imgData = try? Data.init(contentsOf: url)
self.postImage.image = UIImage.init(data: imgData)
Run Code Online (Sandbox Code Playgroud) 确切的错误是:“抛出列表中已经有一个更一般的异常,'java.lang.exception'”
我有一个这样的方法:
public String myMethod() throws FileNotFoundException, IOException, Exception {
try{
// DO STUFF
}catch(FileNotFoundException e){
// DO STUFF
throw new FileNotFoundException("custom message", e);
}catch(IOException e){
// DO STUFF
throw new IOException("custom message", e);
}catch(Exception e){
throw new Exception("custom message", e);
}
return myString;
}
Run Code Online (Sandbox Code Playgroud)
Intellij 告诉我前两个是多余的,因为我最后有更一般Exception的,是这样吗?即使我明确抛出一个,
该方法Exception也会抛出一个IOException吗?
还是无论如何,通用异常都会被抛出堆栈,所以我什至不需要Exception最后?