Custom Exception in Dart programming language - dart

I created a custom exception called DepositeException and trying to access its custom exception message (errorMessage) in main method but it's throwing error. What might be the problem in following code.
void main() {
try {
depositAmount(-100);
} catch (e) {
print(e.errorMessage());
}
}
class DepositException implements Exception {
String errorMessage() {
return "you cannot enter amount less then 0";
}
}
void depositAmount(int amount) {
if (amount < 0) {
throw new DepositException();
}
}

This happen because ~~exception catching in Dart is unchecked~~ the exception type is unspecified so it will return Object (thanks to #jamesdlin for the correction).
To catch the custom exception, you need specify the type like this:
try{
depositAmount(-100);
} on DepositException catch (e){
print(e.errorMessage());
}
Reference:
How to create a custom exception and handle it in dart

Related

how to solve the problem in this code class darts after update

I want to ask something, yesterday I was using Dart version 2.10, after I upgraded to version 2.13, I can't run this code can someone help me
class AmtException implements Exception {
String errMsg() => 'Amount should be greater than zero';
}
void withdraw_amt(int amt) {
if (amt <= 0) {
throw new AmtException();
}
}
void main() {
try {
withdraw_amt(-1);
} catch (e) {
print(e.errMsg());
} finally {
print('Ending requested operation.....');
}
}
This output :
Error: The method 'errMsg' isn't defined for the class 'Object'.
- 'Object' is from 'dart:core'.
Try correcting the name to the name of an existing method, or defining a method named 'errMsg'.
print(e.errMsg());
^^^^^^
The final code:
class AmtException implements Exception {
String errMsg() => 'Amount should be greater than zero';
}
void withdraw_amt(int amt) {
if (amt <= 0) {
throw new AmtException();
}
}
void main() {
try {
withdraw_amt(-1);
} on AmtException catch (e) {
print(e.errMsg());
} finally {
print('Ending requested operation.....');
}
}
Thanks #jamesdlin

Dart The function 'errorMessage' isn't defined

I am new to dart and I am learning dart from youtube. And courses that I am following are of 2018. The programs that they created in their videos are not working. I am facing the below issue in all my programs. Anyone, please guide me that why the programs show errors while the programs are running properly in their videos. Is it happening due to an update in dart? or any other reason? Please help to fix this issue. Thanks!
The function 'errorMessage' isn't defined.
Try importing the library that defines 'errorMessage', correcting the name to the name of an existing function, or defining a function named 'errorMessage'.
class CustomException implements Exception {
String errorMessage() {
return ("Invalid Amount");
}
}
void AmountException(int amount) {
if (amount <= 0) {
throw new CustomException();
}
}
void main() {
try {
AmountException(0);
} catch (e) {
print(errorMessage());
}
}
You are not calling the errorMessage() message on the exception. Another problem is that your catch is set to handle all types of exceptions. Since Exception does not have the errorMessage() method, you cannot call it.
You should therefore specify the type of exception you want to catch which will allow you to call the errorMessage() method on the catched exception:
class CustomException implements Exception {
String errorMessage() {
return ("Invalid Amount");
}
}
void AmountException(int amount) {
if (amount <= 0) {
throw new CustomException();
}
}
void main() {
try {
AmountException(0);
} on CustomException catch (e) {
print(e.errorMessage());
}
}

How to achieve exception chaining in Dart?

In Java, I can achieve exception chaining by passing another exception to the new exception like this:
try {
doSomething();
} catch (Exception1 ex) {
throw new Exception2("Got exception1 while doing the thing", ex);
}
I would like to achieve a similar result in Dart. How can I do that?
One way to do it is like this:
void main(){
try {
try {
throw 'exception 1';
} catch (e) {
throw LinkedException('exception 2',e);
}
} catch (e) {
throw LinkedException('exception 3',e);
}
}
class LinkedException implements Exception {
final String cause;
final exception;
LinkedException(this.cause,[this.exception]);
#override
String toString() => '$cause <- $exception';
}
If you catch the third exception and print it, you would get something like this:
exception 3 <- exception 2 <- exception 1
Dartpad Runnable example: https://dartpad.dev/4000ed0f1e170615923f6c1e7f5f468a

Exception in step at specflow

I'm calling in a function to step (specflow),
Then(step's string)
and in step I throw an exception. I want to catch the exception with a different function and not in the step itself. Do someone know how to do it?
Thanks
This is not possible with SpecFlow.
SpecFlow interprets an exception in an step as error and stops the execution of the Scenario.
What you can do, is to catch the exception in your step and save it in a field of the binding class. Then in the second step you can check this field.
like this:
[Binding]
public class BindingClass
{
private Exception _exception;
[When("an exception is thrown")
public void ExceptionThrown()
{
try {
.... //your code that throws an exception
}
catch(Exception e)
{
_exception = e;
}
}
[Then("the exception has the message '(.*)'")]
public void ExceptionHasTheMessage(string message)
{
if (_exception != null)
{
Assert.Equal(_exception.Message, message);
}
}
}
I use the AfterStep hook available in SpecFlow.
The code looks like this:
[AfterStep]
public void AfterStep()
{
if(_scenarioContext.ScenarioExecutionStatus.ToString().Equals("TestError"))
{
Logger.LogScreenshot(exception, _scenarioContext.ScenarioInfo.Title);
}
}
This piece of code will catch your exception and remaining steps will be skipped.

Stopping Fitnesse (Slim) on any exception

We've found the "Fail Fast" principle crucial for improving maintainability of our large Fitnesse-based battery of tests. Slim's StopTestException is our saviour.
However, it's very cumbersome and counterproductive to catch and convert any possible exception to those custom StopExceptions. And this approach doesn't work outside of fixtures. Is there a way to tell fitnesse (preferably using Slim test system) to stop test on any error / exception?
Update: corresponding feature request https://github.com/unclebob/fitnesse/issues/935
Most of the exceptions coming from fixtures are possible to conveniently convert to the StopTestException by implementing the FixtureInteraction interface, e.g.:
public class StopOnException extends DefaultInteraction {
#Override
public Object newInstance(Constructor<?> constructor, Object... initargs) throws InvocationTargetException, InstantiationException, IllegalAccessException {
try {
return super.newInstance(constructor, initargs);
} catch (Throwable e) {
throw new StopTestException("Instantiation failed", e);
}
}
#Override
public Object methodInvoke(Method method, Object instance, Object... convertedArgs) throws InvocationTargetException, IllegalAccessException {
try {
return super.methodInvoke(method, instance, convertedArgs);
} catch (Throwable e) {
throw new StopTestException(e.getMessage(), e);
}
}
public static class StopTestException extends RuntimeException {
public StopTestException(String s, Throwable e) {
super(s, e);
}
}
}

Resources