1

我知道这种类型的问题以前有过,我已经把它们扔了,但没有得到我需要做的最后一部分。

我的异常类

public class ProException extends Exception {
/**
 * 
 */
private static final long serialVersionUID = 1L;

public ProException(String message) {
    super(message);
  }
}

我的 ActivityClass(Android 中用于 ListView 的自定义适配器)

public View getView(int position, View convertView, ViewGroup parent) {
    View vi = convertView;
    try {
        if (convertView == null) {
            vi = inflater.inflate(R.layout.pause_client_trigger_request_select_sku_list_row, null);
            tvItemName = (TextView) vi.findViewById(R.id.list_row_ItemName);                
        } else {
            tvItemName = (TextView) vi.findViewById(R.id.list_row_ItemName);
        }

        hmap = new HashMap<String, String>();
        hmap = data.get(position);
        tvItemName.setText(hmap.get(KEY_ItemName));

    } catch (ProException ex) {
        Log.i(Tag, ex.getMessage());
    }

    return vi;
}

现在我想要的是。

try catch如果在此任何异常中发生异常。它应该被我的custom class (ProException). 但它不允许。任何帮助

Java Eclipse 编辑器中的消息 Unreachable catch block for ProException. This exception is never thrown from the try statement body

4

4 回答 4

1

所有这些视图都不知道您的自定义异常类。您必须扩展/编写自己的抛出自定义异常的类,或者在块View内手动抛出异常。try

throw new ProException();

于 2013-06-03T10:22:56.650 回答
0

MD 请告诉getView 方法中的哪个调用会抛出ProException。似乎该方法中的任何代码都不会抛出 ProException,因此您会得到“永远不会从 try 语句体中抛出此异常”并且阻止无法访问。为了在 try catch 中使用,它应该获取 Proexception,或者您可以在 getView 的 try catch 中捕获异常,然后将其包装在 ProException 中。

请看看这是否能解决问题。

于 2013-06-03T10:58:30.830 回答
0

ProException 是自定义异常。当代码块抛出异常时,它无法捕获,因为当您编写任何自定义异常时,层次结构变为

Exception->>ProException 

如果代码块抛出任何异常,它将尝试找出 catch 块Exception而不是ProException. 或者简单地说It will try to find out type of exception

所以你必须抓住Exception而不是ProException

每当您将其扔到某个地方时,自定义异常都会很有帮助。

于 2013-06-03T11:25:22.787 回答
0

我想你想要的是

public View getView(int position, View convertView, ViewGroup parent) {
    View vi = convertView;
    try {
        if (convertView == null) {
            vi = inflater.inflate(R.layout.pause_client_trigger_request_select_sku_list_row, null);
            tvItemName = (TextView) vi.findViewById(R.id.list_row_ItemName);                
        } else {
            tvItemName = (TextView) vi.findViewById(R.id.list_row_ItemName);
        }

        hmap = new HashMap<String, String>();
        hmap = data.get(position);
        tvItemName.setText(hmap.get(KEY_ItemName));

    } catch (Exception ex) {
        Log.i(Tag, ex.getMessage());
        throw new ProException(ex.getMessage());
    }

    return vi;
}

然后调用代码可以捕获 ProException。您应该考虑将导致的异常作为 ProException 的构造函数参数(然后您可以将其传递给 super(cause, message))。

于 2013-06-03T12:36:22.267 回答