If you want to catch the exception at another point in the code, don’t catch it at that point, let it bubble to where it needs to be. In fact this method does not even compile.
public static void Inserir(Usuario usuario) {
using var oDB = new estoqueDataClassesDataContext(); //para fazer o dispose correto
oDB.Usuarios.InsertOnSubmit(usuario);
oDB.SubmitChanges();
}
Then you will use:
try {
Inserir(usuario);
} catch (AlgumaExcecaoEspecificaAqui ex) { //não capture Exception
MessageBox.Show(ex.Message); //você pode caprichar mais.
}
See the exception documentation you decided to capture to see everything it has available that you can show. I’m posting the link of documentation of Exception
here, but don’t capture her. See which ones you want to determine that it is useful to show as error.
If you think it’s very important to capture the exception within this method, you can do:
public static string Inserir(Usuario usuario) {
try {
var oDB = new estoqueDataClassesDataContext();
oDB.Usuarios.InsertOnSubmit(usuario);
oDB.SubmitChanges();
} catch (AlgumaExcecaoEspecificaAqui ex) {
return ex.Message;
} finally {
if (oDB != null) ((IDisposable)oDB).Dispose();
}
return "Tudo ocorreu ok";
}
Then you will use:
MessageBox.Show(Inserir(usuario));
You could still get the boolean’s return and the message if you need to do something different:
public static bool Inserir(Usuario usuario, out string nensagem) {
try {
var oDB = new estoqueDataClassesDataContext();
oDB.Usuarios.InsertOnSubmit(usuario);
oDB.SubmitChanges();
} catch (AlgumaExcecaoEspecificaAqui ex) {
menssagem = ex.Message;
return false;
} finally {
if (oDB != null) ((IDisposable)oDB).Dispose();
}
mensagem = "Tudo ocorreu ok";
return true;
}
Then you will use:
string mensagem;
if (Inserir(usuario, out mensagem)) MessageBox.Show(mensagem);
else {
//faz outra coisa aqui que não seja só mostrar a mensagem, para fazer sentido
}
In C# 7 you can do:
public static (bool, string) Inserir(Usuario usuario) {
try {
var oDB = new estoqueDataClassesDataContext();
oDB.Usuarios.InsertOnSubmit(usuario);
oDB.SubmitChanges();
} catch (AlgumaExcecaoEspecificaAqui ex) {
return (false, ex.Message);
} finally {
if (oDB != null) {
((IDisposable)oDB).Dispose();
}
}
return (true, "Tudo ocorreu ok");
}
Then you will use:
var (ok, mensagem) = Inserir(usuario); //talvez tenha uma forma mais conveniente
if (ok) MessageBox.Show(mensagem);
else {
//faz outra coisa aqui que não seja só mostrar a mensagem, para fazer sentido
}
I put in the Github for future reference.
Do you want to show the message you gave in the exception, or do you want to show something else? You don’t understand where the source of your problem is either: http://answall.com/q/101691/101. Visual Basic really? Or is it VB.Net? Or is it actually C#?
– Maniero
show the message you gave in exception. is C#, corrected the post, thanks
– Italo Rodrigo