Throwing and Catching Custom Exceptions

Throwing and Catching Custom Exceptions

The throw keyword is used to explicitly raise an exception. A raised exception should be handled to prevent the program from exiting abruptly. There is two types of exception throwing they are:-** Built-in Exception** and Custom Exceptions.

How can you throw an built-in Exception in dart?

To throw an exception in dart we use throw keyword. Syntax for built-in Exceptions

throw new Exception_name()

Example of built-in expection The following example shows how to use throw keyword for throwing an exception:-

void checkNumber(int number) {
  if (number %2 == 0) {
    throw Exception('Even numbers are not allowed');
  } else {
    print('The number  $number is odd');
  }
}

void main() {
  try {
    checkNumber(5);
  } catch (e) {
    print('Caught an exception: $e');
  } finally {
    print('Finally block is executed irrespective of exception's occurrence');
  }
}

Output

Caught an exception: Exception: Even numbers are not allowed
Finally block is executed irrespective of exception's occurrence

code Try Yourself

How can you throw an custom Exception in dart?

Every exception type in Dart is a subtype of the bult-in class Exception. Dart enables creating custom exceptions by extending the exisiting ones.

Syntax for Custom Exceptions

class Custom_exception_Name implements Exception(){
`//can contain methods variables
}

Example of Custom Exceptions

class NegativeNumberException implements Exception {
  final String message;
  NegativeNumberException(this.message);
  
  @override
  String toString() => 'NegativeNumberException: $message';
}

void checkNumber(int number) {
  if (number < 0) {
    throw NegativeNumberException('Negative numbers are not allowed');
  } else {
    print('The number is $number');
  }
}

void main() {
  try {
    checkNumber(-5);
  } catch (e) {
    print('Caught an exception: $e');
  } finally {
    print('Finally block is executed irrespective of exception's occurrence');
  }
}

Output:-

Caught an exception: NegativeNumberException: Negative numbers are not allowed
Finally block is executed irrespective of exception's occurrence

code Try Yourself