Skip to content

Instantly share code, notes, and snippets.

@kwalrath
Forked from Sfshaza/main.dart
Created August 16, 2018 21:25
Show Gist options
  • Save kwalrath/63e040a3fd682e191af40f6427eaf9ef to your computer and use it in GitHub Desktop.
Save kwalrath/63e040a3fd682e191af40f6427eaf9ef 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 Circle(2);
if (type == 'square') return 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(Shape('circle').area);
print(Shape('square').area);
print(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