How can I throw exception from my code?

edited September 2014 in Using Processing

Hi everyone,

I am new to Processing but I have a far background in Java and strong C# skills. So my problem might be related to my poor Java knowledge, but even after reading documentation, it seems that my code is throwing exceptions properly.

Here is a sample code:

void setup() {
    Dummy d = new Dummy(10);
}

public class Dummy {
    int _n;

    public Dummy(int n) {
        if (n == 0) {
            throw new Exception("Cannot be 0.");
        }

        _n = n;
    }
}

For example here, the compiler will always fail to build and return this uninformative error:

test.pde:11:0:11:0: Unhandled exception type Exception

What is wrong with my exception throwing and how can I fix it?

Answers

  • You have to mark the method as throwing an exception

    public Dummy(int n) throws Exception {
        if (n == 0) {
            throw new Exception("Cannot be 0.");
        }
    
  • Answer ✓

    As GoToLoop points out you could use a RuntimeException this is an unchecked exception which means you don't have to catch it. The choice is yours and you might want to do some research on which to use.

    Personally I prefer to use checked exceptions because it forces me to deal with the fact my code has hit a problem. It helps the me develop stronger more resilient code.

  • edited September 2014

    So as you guys suggested I dug further in the Java exceptions documentation and I discovered about the 2 groups of exceptions (checked and unchecked). In my case it is a parameter issue, which is unlikely to be recoverable in a program flow therefore I will opt for InvalidParameterException which is a subclass of RuntimeException (unchecked).

    import java.security.*;
    
    void setup() {
        Dummy d1 = new Dummy(10);
        Dummy d2 = new Dummy(0);
    }
    
    public class Dummy {
        int _n;
    
        public Dummy(int n) {
            if (n == 0) {
                throw new InvalidParameterException("n cannot be 0.");
            }
    
            _n = n;
            println("Dummy: " + _n);
        }
    }
    
  • InvalidParameterException belongs to the java.security package, which seems a bit specialized. While it isn't really important, in your use case, Java coders tend to use IllegalArgumentException instead.

    And you are right, checked exceptions should be used mostly in case of recoverable errors, while your exception is more like an assert, and is raised only in the case of a programming error. Forcing callers of the function to catch exceptions would be heavy handed.

    Actually, most modern JVM languages renounced the checked exceptions, a feature only Java (AFAIK) supports.

  • I, too, would like to throw exception from my code....

    as far away as possible!

  • Well, don't. Your sketches should be exceptional!

Sign In or Register to comment.