Exception in PL:SQL
Exception in PL:SQL
1. Exception Handling
a) Predefined Exceptions
These are system-defined exceptions that occur during runtime. Some common
predefined exceptions:
Example:
BEGIN
SELECT salary INTO v_salary FROM employees WHERE id = 101;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No record found.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Some other error occurred.');
END;
/
b) User-Defined Exceptions
You can define your own exceptions using the EXCEPTION keyword.
Example:
Exception in PL/SQL 1
DECLARE
insufficient_balance EXCEPTION;
balance NUMBER := 500;
BEGIN
IF balance < 1000 THEN
RAISE insufficient_balance;
END IF;
EXCEPTION
WHEN insufficient_balance THEN
DBMS_OUTPUT.PUT_LINE('Balance is too low.');
END;
/
2. Cursors
Cursors are used to retrieve multiple rows from a database.
a) Declaring a Cursor
DECLARE
CURSOR emp_cursor IS SELECT id, name FROM employees;
BEGIN
OPEN emp_cursor;
FETCH emp_cursor INTO v_id, v_name;
END;
c) Closing a Cursor
CLOSE emp_cursor;
Exception in PL/SQL 2
d) Explicit vs Implicit Cursors
Implicit Cursor: Automatically created by PL/SQL for SELECT statements.
DECLARE
CURSOR emp_cursor(dept_id NUMBER) IS
SELECT id, name FROM employees WHERE department = dept_id;
3. Procedures
Procedures are stored subprograms that execute a set of SQL statements.
To drop a procedure:
b) Calling Procedures
DECLARE
v_salary NUMBER;
BEGIN
get_salary(101, v_salary);
DBMS_OUTPUT.PUT_LINE('Salary: ' || v_salary);
Exception in PL/SQL 3
END;
/
Exception in PL/SQL 4