xxxxxxxxxx
void validate_age(int age) {
if(age < 0) {
throw new FormatException();
}
}
xxxxxxxxxx
class CustomException implements Exception {
String cause;
CustomException(this.cause);
}
void main() {
try {
throwException();
} on CustomException {
print("custom exception has been obtained");
}
}
throwException() {
throw new CustomException('This is my first custom exception');
}
xxxxxxxxxx
void someFunction() {
// Some condition to check for an error
bool isErrorOccurred = true;
if (isErrorOccurred) {
// Throw an error with a custom message
throw 'An error occurred!';
}
// Other code if no error occurred
// ...
}
xxxxxxxxxx
void main() {
try {
someFunction();
} catch (e) {
print('Caught an error: $e');
// Handle the error here, such as showing a user-friendly error message
}
}