Answers for "flutter try catch example"

7

dart try-catch

try {
  // ...
} on SomeException catch(e) {
 //Handle exception of type SomeException
} catch(e) {
 //Handle all other exceptions
}
Posted by: Guest on December-09-2020
5

dart try

HOW TO HANDLE EXCEPTIONS IN DART/FLUTTER!

# ------------------------ CASE 1: --------------------------- #
When you know the exception to be thrown, use ON Clause
	try {
		int result = 12 ~/ 0;
		print("The result is $result");
	} on IntegerDivisionByZeroException {
		print("Cannot divide by Zero");
	}

# ------------------------ CASE 2: --------------------------- #
When you do not know the exception use CATCH Clause

	try {
		int result = 12 ~/ 0;
		print("The result is $result");
	} catch (e) {
		print("The exception thrown is $e");   
	}

# ------------------------ CASE 3: --------------------------- #
Using STACK TRACE to know the events that occurred before the
Exception was thrown (trace and print the code steps after the 
error)

	try {
		int result = 12 ~/ 0;
		print("The result is $result");
	} catch (e, s) {
		print("The exception thrown is $e");
		print("STACK TRACE n $s");
	}

# ------------------------ CASE 4: --------------------------- #
Whether there is an Exception or not, FINALLY Clause is always 
Executed

	try {
		int result = 12 ~/ 3;
		print("The result is $result");
	} catch (e) {
		print("The exception thrown is $e");
	} finally {
		print("This is FINALLY Clause and is always executed.");
	}

# ------------------------ CASE 5: --------------------------- #
Custom Exception.The throw keyword is used to explicitly raise 
an exception, and, in this case, that exception was defined by 
the following exemple: 

void main(){

	try {
		depositMoney(-200);
	} catch (e) {
		print(e.errorMessage());
	} finally {
		// Code
	}
}

class DepositException implements Exception {
	String errorMessage() {
		return "You cannot enter amount less than 0";
	}
}

void depositMoney(int amount) {
	if (amount < 0) {
		throw new DepositException();
	}
}
Posted by: Guest on September-05-2020
0

try except flutter

try {
  print(x);
} on Exception catch (_) {
  print('never reached');
}
Posted by: Guest on July-18-2021

Code answers related to "Dart"

Browse Popular Code Answers by Language