Roughly you can do it like that :
try
{
//do something
}
catch (Exception ex)
{
string script = "<script>alert('" + ex.Message + "');</script>";
if (!Page.IsStartupScriptRegistered("myErrorScript"))
{
Page.ClientScript.RegisterStartupScript("myErrorScript", script);
}
}
But I recommend you to define your custom Exception and throw it anywhere you need. At your page catch this custom exception and register your message box script.