Apex classes have concept of Exception handling. This is similar to all other languages.
You can create an custom Exception class by extending the standard
Exception class of the Apex.
You should go through following documentation: An Introduction to Exception Handling
By implementing your own Exception class class whenever you want to interrupt the code simply throw exception as:
throw new MyCustomException(' The Error Message');
// Own exception class extending the standard Exception class.
throw new MyException('something bad happened!');
catch (MyException e)
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'my error msg');
If you want to let the error come directly to user interface, do not cover statements with
try-catch (this is not recommended).