Exception Handling¶
throw¶
Description¶
The throw
statement indicates that an exception or error occurred during the Application's execution.
Syntax¶
throw exception;
where exception is a BusinessException
Example¶
BusinessException e = BusinessException.Create("Something went horribly wrong.");
throw e;
var existing = Domain.ApplicationUser.GetAll().Where(x => x.UserName != user.UserName && x.Email == user.Email).First();
if(existing != null){
throw BusinessException.Create("A user with this e-mail has already been registered.");
}
try-catch¶
Description¶
The try-catch statement is used to handle exceptions, providing a graceful way to define "what to do if something goes wrong".
If an Exception is thrown and there is no catch
statement to handle it, it will produce an Error in the Application, providing information with regards to the immediate call stack of the faulted method and a descriptive message. If there is a catch
, then it is up to the user (developer) to decide and code how such an occurrence is to be handled.
You can define as many catch
statements as you wish, one catch
per type of Exception. This way, you can define one handler for a BusinessException
, another for a generic Exception
etc.
Syntax¶
try {
run_this;
}
catch Exception x {
run_that;
}
Example¶
try {
int ten = 10;
int zero = 0;
int noway = ten / zero;
}
catch Exception x {
ShowMessage(x.Message); //Shows: "Attempted to divide by zero."
DebugLib.Logger.WriteErrorLine(x.StackTrace);
}
try {
int ten = 10;
int zero = 0;
int noway = ten / zero;
}
catch Exception x {
// Silent exception.. Act like nothing ever happened
}
try {
int ten = 10;
int zero = 0;
int noway = ten / zero;
}
catch BusinessException businessException {
ShowMessage(businessException.Message);
}
catch Exception exception {
DebugLib.Logger.WriteInfoLine(
"Caught an unexpected Exception. " +
"Message: " + exception.Message +
", StackTrace: " + exception.StackTrace);
throw exception;
}
try-catch-finally¶
Description¶
The finally
statement of a try-finally block, runs right after the try
, even if the latter produced an exception. Simply put, the finally
statement is a statement that will always run, no matter what. You can use it to clean up any resources you might been using during its try
.
Info
Contrary to other languages (e.g. C# etc.), Mamba does not have a try-finally
statement.
Since a finally
statement that runs after an unhandled exception might result into unexpected behavior, the best practice is to always call finally
after a handled exception.
Syntax¶
try{
run_this;
}
catch Exception e{
catch_thrown_exception;
}
finally {
run_that_no_matter_what;
}
Exception¶
try{
Model.User.Delete();
}
catch Exception e {
DebugLib.Logger.WriteErrorLine(
"Caught an exception while deleting User [" + Model.User.UserName + "]." +
"Message: " + e.Message + ", " +
"StackTrace: " + e.StackTrace
);
}
finally {
//Close the form, after Deleting the User, no matter what
CloseForm();
}