PL/SQL SAMPLE PROGRAM # 2

rem  This program is a modification of SAMPLE1

rem  An exception is raised if the user passes a value <= 0
 

set serveroutput on size 20000

declare

 i binary_integer;
 upper_limit binary_integer;
 sum_ints binary_integer;
 invalid_limit exception;   -- declares the exception

begin
--  Loop to add:

 sum_ints := 0;
 upper_limit := &1;

 if upper_limit <= 0 then
   raise invalid_limit;
 end if;

 for i in 1..upper_limit loop
  sum_ints := sum_ints + i;
 end loop;

--  Display the total:

 dbms_output.new_line;
 dbms_output.put_line ('The sum of the integers from 1 to ' ||
               upper_limit || ' is: ' || sum_ints);

exception

 when invalid_limit then
  dbms_output.put_line ('Upper limit must be > 0');

end;
/