C# try catch doesnt seem to work

Hi this is my first post on here. Ive looked around and cant seem to find an answer to this. My code for try/catch doesnt seem to work:

bool CheckNewPosition(int _direction) {
    try { 
        shapeX ++; 
    } 
    catch () { 
        print("error"); 
    }   
}

the error is:

"Expected catch or finally"

Any help would be great.

2 Likes
bool CheckNewPosition(int _direction) {
    try {
        shapeX ++;
    }
    catch (Exception e) {
        print("error");
    }   
}
6 Likes

Thanks for your reply, I tried this and now get an error:

"The type or namespace name `Exception' could not be found. Are you missing a using directive or an assembly reference?"

1 Like

On the first line of your program, add the following code:

using System;
11 Likes

Thankyou! Simple when you know how :slight_smile:

1 Like

Some times missing something simple as using System; gives lot of head ache! eh :smile:

1 Like

You can optionally forego referencing the exception object if you're uninterested in the error's details.

try {
    // Do something
} catch {
    Debug.Log("Horrible things happened!");
}

i tried doing this in my build. it gets rid of the ‘Exception’ error but it messes up my ‘Random’ codes. what’s up with that? sorry. newbie

Either don’t import System and specify System.Exception in the code instead, or else import System and specify UnityEngine.Random.

–Eric

2 Likes

What kind of exception do you expect? In case of OverflowException shouldn’t it be like this?

bool CheckNewPosition(int _direction)
{
    try
    {
        checked
        {
            shapeX++;
        }
    }
    catch (OverflowException)
    { 
        print("error"); 
    }	
}