This is a followup to the "Hello World" walkthrough.
actor Main
new create(env: Env) =>
try
env.out.print(env.args(1))
else
env.out.print("oops")
end
The first two lines of this program are the same as the "Hello World"
program. To recap, they represent the entry point of the program by
defining an actor called Main
with a constructor called create
that accepts a single argument of type Env
. This is required for all
Pony programs.
What is different from the "Hello World" program is the body of the
create
constructor. The program is still printing a string, but is
now considering outside input when deciding what to print.
If you're familiar with languages that have exceptions, you can probably figure out what is going on based on the syntax, but it may seem strange that printing would require this construct.
The try
keyword opens a block of code that may throw an exception.
The else
keyword closes that block, and opens a new block that will
run only if an exception is thrown in the previous block. The end
keyword closes the else
block.
As mentioned in the "Hello World" walkthrough, the Env
type provides
access to things that are normally globally available. In this case,
the program needs access to the string arguments passed into the
porgram at the command line. Pony stores these arguments in the args
field of Env
as a string array, which has the type Array[String]
.
The expression env.args(1)
is showing off some of Pony's syntactic
sugar. The expression expands to env.args.apply(1)
. That is, the
method apply
is called on the string array args
of the env
variable, with the argument 1
. There is more too this syntax, but
for now, it can be assumed that if a variable is being called like a
method, then under the hood, the apply
method is actually being
called.
So, where does the exception come from? An exception is thrown if the index provided for an array lookup is out of bounds. In many languages, this consitutes a runtime exception and is not required to be handled. However, Pony checks this at compile time.
The compiler will either require the array lookup to occur in a try
block, or for the programmer to indicate that the error should be
propogated. In this case, the program is required to handle the
exception because create
constructor on Main
cannot be marked to
propogate the exception.
The else
block will handle the exception and print oops
to the
screen. This will happen if no args are passed to the program. If an
else
block was not provided, the exception would still be handled,
but be silently ignored.