LoginSignup
0
0

More than 3 years have passed since last update.

Processingでエラーを投げたいときどうするか?

Last updated at Posted at 2020-11-09

やりたいこと

  • 引数として好ましくないものが与えられたときプログラムを終了させたい
    • return;などでプログラムを終わらせるのではなく、
    • 明示的にエラーを返し終了させたい

環境

  • LinuxMint 20
  • Processing 3.5.4

サンプルコード

たとえば次のようなBallクラスを考える。
コンストラクタに与えられる引数_radiusによって描画されるボールの半径が決まる仕組みになっている。

Before

ball.pde
class Ball {
    float radius;
    Ball(float _radius) {
        radius = _radius;
    }

    public void draw() {
        fill(0, 255, 0);
        ellipse(mouseX, mouseY, radius, radius);
    }
}

おおまかにはこれで構わないかもしれないが、もし誤って引数_radiusに0やマイナスの値が代入された場合、Processingがどのような挙動を示すかわからない。

そこで、引数に正でない数が入力された場合エラーを吐くように書き換えておくことにする。

After

ball.pde
import java.lang.*;

class Ball {
    float radius;
    Ball(float _radius) throws IllegalArgumentException {
        if (_radius > 0) {
            radius = _radius;
        } else {
            throw new IllegalArgumentException("【エラー】半径は正でなければなりません!");
        }
    }

    public void draw() {
        fill(0, 255, 0);
        ellipse(mouseX, mouseY, radius, radius);
    }
}

ポイント

  1. 関数名のあとにthrows IllegalArgumentExceptionを付ける1
  2. エラーの投げ方は、throw new IllegalArgumentException(/*エラーメッセージ*/);
  3. Javaの機能を用いているので、import java.lang.*;を忘れずに

参考

How can I throw exception from my code? - Processing 2.x and 3.x Forum


  1. throwではなくthrowsであることに注意 

0
0
0

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
0
0