抛出IOException以下代码中的错误

时间:2010-10-18 05:45:30

标签: java

import java.io.*;
import java.lang.*;

public class Propogate1
{

String reverse(String name)
{
if(name.length()==0)
    throw IOException("name");

String reverseStr="";
for(int i=name.length()-1;i>0;--i)
{
  reverseStr+=name.charAt(i);

}
return reverseStr;
}

public static void main(String[] args)throws IOException
{
String name;
try
{
        Propogate1 p=new Propogate1();
    p.reverse("java");

}
finally
{
System.out.println("done");
}

}

}

我必须创建一个类propogate和main方法,它将调用reverse()。如果name.length为null,则会抛出异常。如果它不为null,它将反转字符串。请帮助我

3 个答案:

答案 0 :(得分:1)

您需要声明方法中抛出哪些异常:方法声明应为:

String reverse(String name) throws IOException

答案 1 :(得分:1)

你必须在抛出之前创建异常:

if(name.length()==0)
    throw new IOException("name");

主要不能抛出IOException。抓住它并将消息打印到System.err

答案 2 :(得分:1)

可能这就是你需要的。

package reversestring;

// import java.io.* is not needed here. 
// And if you want to import anything,
// prefer specific imports instead and not entire package.

// java.lang.* is auto-imported. You needn't import it explicitly.      

public class Propogate {
  // There's no reason this method should be an object method. Make it static.
  public static String reverse(String name) {
    if (name == null || name.length() == 0) {
      // RuntimeExceptions are preferred for this kind of situations.
      // Checked exception would be inappropriate here.
      // Also, the error message should describe the kind of exception
      // occured.
      throw new RuntimeException("Empty name!");
    }
    // Idiomatic method of string reversal:
    return new StringBuilder(name).reverse().toString();
  }

  public static void main(String[] args) {
    String name;
    try {
      name = Propogate.reverse("java");
      System.out.println("Reversed string: " + name);
    } catch (RuntimeException rx) {
      System.err.println(rx.getMessage());
    } finally {
      // I don't get the point of `finally` here. Control will reach this
      // point irrespective of whether string reversal succeeded or failed.
      // Can you explain what do you mean by "done" below?
      System.out.println("done");
    }
  }
}
  

/ *

     

输出: -

     

反转字符串:avaj

     

完成

     

* /