LoginSignup
2
2

More than 5 years have passed since last update.

例外の書き方をまとめた

Last updated at Posted at 2014-02-09

いつもモヤモヤしてたので、一度まとめてみました。

MainActivity.java
HogeProfile profile = new HogeProfile();
try {
    service.postProfile(profile);
    Toast.makeText(this, "登録が完了しました", Toast.LENGTH_SHORT).show();
} catch (HogeNotFoundUserException e) {
    Toast.makeText(this, "ユーザーが見つかりません", Toast.LENGTH_LONG).show();
} catch (HogeInvalidParameterException e) {
    Toast.makeText(this, "入力に不備があります", Toast.LENGTH_LONG).show();
} catch (HogeServerMaintenance e) {
    Toast.makeText(this, "サーバーがメンテナンス中です", Toast.LENGTH_LONG).show();
}
MainActivity2.java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    HogeProfile profile = new HogeProfile();
    try {
        service.postProfile(profile);
        Toast.makeText(this, "登録が完了しました", Toast.LENGTH_SHORT).show();
    } catch (HogeException e) {
        handleException(e);
    }
}

private void handleException(HogeException e) {
    if (e instanceof HogeNotFoundUserException) {
        Toast.makeText(this, "ユーザーが見つかりません", Toast.LENGTH_LONG).show();
    } else if (e instanceof HogeInvalidParameterException) {
        Toast.makeText(this, "入力に不備があります", Toast.LENGTH_LONG).show();
    } else if (e instanceof HogeServerMaintenance) {
        Toast.makeText(this, "サーバーがメンテナンス中です", Toast.LENGTH_LONG).show();
    }
}
MainActivity3.java
HogeProfile profile = new HogeProfile();
HogeServiceResult result = service.postProfile(profile);
if (result.hasError()) {
    HogeException e = result.getException();
    if (e instanceof HogeNotFoundUserException) {
        Toast.makeText(this, "ユーザーが見つかりません", Toast.LENGTH_LONG).show();
    } else if (e instanceof HogeInvalidParameterException) {
        Toast.makeText(this, "入力に不備があります", Toast.LENGTH_LONG).show();
    } else if (e instanceof HogeServerMaintenance) {
        Toast.makeText(this, "サーバーがメンテナンス中です", Toast.LENGTH_LONG).show();
    }
} else {
    Toast.makeText(this, "登録が完了しました", Toast.LENGTH_SHORT).show();
}
MainActivity4.java
HogeProfile profile = new HogeProfile();
HogeServiceResult result = service.postProfile(profile);
HogeServiceResultResolver.resolver(result);
```
2
2
9

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2