Skip to content

Instantly share code, notes, and snippets.

@Sfshaza
Last active August 16, 2018 21:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Sfshaza/56381ac0a35594844919150039dcf214 to your computer and use it in GitHub Desktop.
Save Sfshaza/56381ac0a35594844919150039dcf214 to your computer and use it in GitHub Desktop.
Java-to-Dart codelab: Using a try-catch statement
import 'dart:math';
abstract class Shape {
factory Shape(String type) {
if (type == 'circle') return new Circle(2);
if (type == 'square') return new Square(2);
// To trigger exception, don't implement a check for 'triangle'.
throw 'Can\'t create $type.';
}
num get area;
}
class Circle implements Shape {
final num radius;
Circle(this.radius);
num get area => PI * pow(radius, 2);
}
class Square implements Shape {
final num side;
Square(this.side);
num get area => pow(side, 2);
}
class Triangle implements Shape {
final num side;
Triangle(this.side);
num get area => pow(side, 2) / 2;
}
main() {
try {
print(new Shape('circle').area);
print(new Shape('square').area);
print(new Shape('triangle').area);
} catch (err) {
print(err);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment