Doug Null
Doug Null

Reputation: 8327

Can MatLab 'catch' be at higher level than 'try'?

Is it possible in MatLab to throw an exception in a nested function, and have it 'caught' by a higher up function, such as in C++ or Visual Basic?

Upvotes: 2

Views: 116

Answers (1)

patrik
patrik

Reputation: 4558

It is quite possible to catch exceptions in a higher level then they occur. What I do not think works, is to catch exceptions on another level than where the try is. I am not sure about that though. The try catch is fairly simple to implement in matlab. It really solves itself in some auto- magical way. It is possible to throw exceptions inside try block and then it will be caught in the catch. It is also possible to just surround the code that may go wrong inside a try block and then catch the exception.

Using throw:

function mymain()
    x=[1,2];
    try
        myfun(x);
    catch me
        disp(me);
        error(me.message);
    end
end

function myfun(x)
    if (length(x)>1)
        throw(MException('MATLAB:badsubscript','x must be scalar!'));
    end
end

Using nothing:

function mymain2()
    x=[1,2];
    try
        myfun2(x);
    catch me
        disp(me);
        error(me.message);
    end
end

function myfun2(x)
    x(7);
end

The variable me is not defined in the sense that you yourself actually defines a variable me. It is rather matlab that creates an exception and then the exception is stored in the variable defined in the catch.

Upvotes: 1

Related Questions