0% found this document useful (0 votes)
5 views

PLSQL

PL/SQL is a programming language for managing data in databases, combining SQL and procedural features for application development. It includes features like error checking, logging, and the ability to handle multi-row queries with cursors. PL/SQL supports various data types, constants, and variable declarations, allowing for efficient data manipulation and control within Oracle databases.

Uploaded by

JOHAAN MATHEW
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

PLSQL

PL/SQL is a programming language for managing data in databases, combining SQL and procedural features for application development. It includes features like error checking, logging, and the ability to handle multi-row queries with cursors. PL/SQL supports various data types, constants, and variable declarations, allowing for efficient data manipulation and control within Oracle databases.

Uploaded by

JOHAAN MATHEW
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Unit 5

What is PL/SQL
PL/SQL, in simple terms, is a programming language used for managing
data in databases. It combines SQL for data manipulation and
procedural features for building applications. It's like a toolkit that lets
you efficiently interact with and control your Oracle database.

Features of PL/SQL :
The various features of PL/SQL are given below –
 PL/SQL runs on various operating systems such as windows, Linux
etc.
 PL/SQL have an error-checking facility and displays user-friendly
messages when an error occurs in a program.
 It offers logging and debugging capabilities, including the capacity to
use exception messages.
 SQL can be executed dynamically.
 When certain data events, such as INSERT, UPDATE, or DELETE
actions on a table, occur, triggers are specialized forms of stored
processes that are automatically invoked.
 Multi-row queries are handled using cursors.
 The declaration of variables and constants to store data values is
supported.

What do you mean by PL/SQL Architecture?


The PL/SQL runtime system is a technology and not an independent
product. This technology is actually like an engine that exhibits PL/SQL
blocks, subprograms like functions and procedures. This engine can be
installed in an Oracle Server or in application development tools such as
Oracle Form Builder, Oracle Reports Builder etc.
Advantages of PL/SQL :
 PL/SQL provides better performance.
 PL/SQL has high Productivity.
 It supports Object-Oriented Programming concepts.
 It has Scalability and Manageability.
 PL/SQL supports various Web Application Development tools.

Disadvantages of PL/SQL :
 PL/SQL requires high memory.
 Lacks of functionality debugging in stored procedures.

Blocks in PL/SQL

In PL/SQL, All statements are classified into units that is called Blocks.
PL/SQL blocks can include variables, SQL statements, loops, constants,
conditional statements and exception handling. Blocks can also build a
function or a procedure or a package.

The Declaration section: Code block start with a declaration section, in


which memory variables, constants, cursors and other oracle objects can
be declared and if required initialized.
The Begin section: Consist of set of SQL and PL/SQL statements,
which describe processes that have to be applied to table data. Actual
data manipulation, retrieval, looping and branching constructs are
specified in this section.
The Exception section: This section deals with handling errors that
arise during execution data manipulation statements, which make up
PL/SQL code block. Errors can arise due to syntax, logic and/or
validation rule.
The End section: This marks the end of a PL/SQL block.

Broadly, PL/SQL blocks are two types : Anonymous blocks and Named
blocks are as follows:
1. Anonymous blocks: In PL/SQL, That’s blocks which is not having
header are known as anonymous blocks. These blocks do not form the
body of a function or triggers or procedure. Example: Here a code
example of find greatest number with Anonymous blocks.
 SQL
DECLARE
-- declare variable a, b and c
-- and these three variables datatype are integer
a number;
b number;
c number;
BEGIN
a:= 10;
b:= 100;
--find largest number
--take it in c variable
IF a > b THEN
c:= a;
ELSE
c:= b;
END IF;
dbms_output.put_line(' Maximum number in 10 and 100: ' || c);
END;
/
-- Program End
Output:
Maximum number in 10 and 100: 100

2. Named blocks: That’s PL/SQL blocks which having header or labels


are known as Named blocks. These blocks can either be subprograms
like functions, procedures, packages or Triggers. Example: Here a code
example of find greatest number with Named blocks means using
function.

 SQL
DECLARE

-- declare variable a, b and c


-- and these three variables datatype are integer
DECLARE
a number;
b number;
c number;
--Function return largest number of
-- two given number
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;
RETURN z;
END;
BEGIN
a:= 10;
b:= 100;
c := findMax(a, b);
dbms_output.put_line(' Maximum number in 10 and 100
is: ' || c);
END;
/
-- Program End
Output:
Maximum number in 10 and 100: 100

PL/SQL Constants

In PL/SQL, constants are declared with the help of


the CONSTANT keyword, followed by data type and initialization of
value. They are especially useful in scenarios where the fixed value is
required multiple times but most remain unchanged to avoid
unintended modifications or errors.
Characteristics of PL/SQL Constants:
 Immutable: Once initialized, their value cannot be changed further.
 Declaration: Constants must be assigned a value at the time of the
declaration.
 Readability: Enhances the code clarity and makes it easier to
understand and maintain.
 Performance: Reduces the overload of the repeated calculations or
lookups by the storing the fixed value.
Syntax:
DECLARE
constant_name CONSTANT data_type := value;
BEGIN
-- Code block where the constant can be used
END;
Explanation:
 constant_name: The name of the constant should be a variable. The
name must be meaningful and should follow the PL/SQL naming
conventions.
 CONSTANT: The keyword is indicating that the value is assigned to
constant cannot change after the initialization.
 data_type: The data type of constant like NUMBER,
VARCHAR2 or DATE.
 := : This is assignment operator which is used to initialize constant
with the value.
 value: The value that is assigned to constant, which cannot be
modified the later.

Example 1: Using a Constant in a Simple Arithmetic Operation

 By Using a Constant in a Simple Arithmetic Operation, pi is


declared as the constant with value 3.14159 .
 The radius is assigned value 5, and the area of circle is calculated
with the help of formula pi * radius^2 .
 The result of calculation is displayed withe
the DBMS_OUTPUT.PUT_LINE .
Query:
DECLARE
pi CONSTANT NUMBER := 3.14159;
radius NUMBER := 5;
area NUMBER;
BEGIN
area := pi * radius * radius;
DBMS_OUTPUT.PUT_LINE('Area of the circle: ' || area);
END;
/
Output:
Area of the circle: 78.53975
Explanation:
 In the above output, the constant pi is used in formula and since it
cannot be changed, it is ensure that consistent results for all
the calculations involving it.
Example 2: Using Constants in Conditional Logic
In PL/SQL, constants are fixed values that cannot be changed once
defined. In the example, min_age is declared as a constant with a value
of 18, representing the minimum voting age.
The conditional IF statement checks if the user_age (set to 20) is
greater than or equal to min_age, determining the user's eligibility to
vote. Since user_age is 20, the output is "User is eligible to vote."
Query:
DECLARE
min_age CONSTANT NUMBER := 18;
user_age NUMBER := 20;
BEGIN
IF user_age >= min_age THEN
DBMS_OUTPUT.PUT_LINE('User is eligible to vote.');
ELSE
DBMS_OUTPUT.PUT_LINE('User is not eligible to vote.');
END IF;
END;
/
Output:
User is eligible to vote.
Explanation:
 In the above code, min_age is the constant with
value 18, representing minimum voting age.
 user_age is assigned the value 20.
 A conditional statement is checks whether the user_age is greater
than or equal to the min_age to determine the eligibility to the vote.
Example 3: Constant with String Data Type
 In given below example company_name is the constant with
value Tech Innovators Inc. where Constant with String Data type is
used.
 The employee_name is initialized with value John Doe .
 The program outputs the message that concatenates employee name
and the name of the company.
Query:
DECLARE
company_name CONSTANT VARCHAR2(50) := 'Tech Innovators
Inc.';
employee_name VARCHAR2(30) := 'John Doe';
BEGIN
DBMS_OUTPUT.PUT_LINE('Employee ' || employee_name || ' works
at ' || company_name);
-- Trying to change company_name will cause an error
-- company_name := 'New Company'; -- This would generate a
compilation error
END;
/
Output:
Employee John Doe works at Tech Innovators Inc.
Explanation:
 Here, the constant company_name is ensure that company name is
remain fixed throughout the program. Attempting to change
the company_name would give the compilation
error highlighting immutability of the constants.

Variables:

How to Declare PL/SQL Variables?


When writing PL/SQL code it is important to declare variables properly
to store and manipulate data effectively. Variables act as containers for
values and enable various operations on the stored data.

Common Methods for Declaring Variables in PL/SQL


The below methods are used to declare a variable in PL/SQL are as
follows:
 Using Declare Variables in PL/SQL
 Using Initializing Variables in PL/SQL
 Using Variable Scope in PL/SQL
 Using Variable Attributes

Let's understand each method one be one along with the Examples.
1. Using Declare Variables in PL/SQL
To declare a variable in PL/SQL, use the DECLARE keyword followed
by the variable name and its data type. Optionally, you can also assign
an initial value to the variable using the ':=' operator.

Syntax:

DECLARE
variable_name datatype := initial_value;
here,
 variable_name: It is the name of the variable.
 datatype: It is the data type of the variable.
 := initial_value: It is an optional assignment of an initial value to the
variable.

Example:

DECLARE
name VARCHAR2(20) := 'GeeksForGeeks';BEGIN
DBMS_OUTPUT.PUT_LINE(name);END;
Output:

Output

Explanation: In the above Query, We have declares a variable named


"name" with a size of 20 characters and initializes it with the
value GeeksForGeeks then prints the value of the variable
using DBMS_OUTPUT.PUT_LINE.

2. Using Initializing Variables in PL/SQL


In this method Variables can be initialized in two ways either during
declaration or later in the code.

a. Initializing during declaration

Variables can be assigned values when declared, as shown below:


Syntax:
DECLARE
my_variable NUMBER := value;
BEGIN
-- PL/SQL code
END;
Example:
DECLARE
name VARCHAR2(20) := 'GeeksForGeeks';BEGIN
DBMS_OUTPUT.PUT_LINE(name);END;
Output:

b. Initialization After Declaration

You can also assign a value to a variable later in the code using the :=
operator.
Syntax:
DECLARE
my_variable NUMBER;BEGIN
my_variable := value;END;
Example:
DECLARE
num1 NUMBER;
num2 NUMBER;
result NUMBER;BEGIN
num1 := 5;
num2 := 3;
result := num1 + num2;
DBMS_OUTPUT.PUT_LINE('Sum: ' || result);END;
Output:

2. Using Variable Scope in PL/SQL


Variable scope determines where a variable can be accessed within a
program. In PL/SQL, variable scope can be either local or global.
 Local Variables: Declared within a block or subprogram, accessible
only inside that block or subprogram.
 Global Variables: Declared in the outermost block and accessible by
nested blocks.

Example:

DECLARE
global_var NUMBER; -- global variableBEGIN
-- PL/SQL code using global_var
DECLARE
local_var NUMBER; -- local variable
BEGIN
-- PL/SQL code using local_var and global_var
END;
-- Here you can't access local_var END;

Explanation: The global_var can be accessed throughout the entire


program, while the local_var is only accessible within the inner block

4. Using Variable Attributes (%TYPE and %ROWTYPE)


PL/SQL provides two powerful attributes, %TYPE and %ROWTYPE,
which allow variables to inherit data types from existing columns or
entire rows.
 %TYPE: It defines a variable with the same data type as another
variable or column.
 %ROWTYPE: It defines a record with the same structure as a table
or cursor.

Example: The below example is demonstrating the use of %TYPE


and %ROWTYPE attribute
Create a employees table and Insert some records into a employees
table
-- Creating a employees table CREATE TABLE employees (
employee_id NUMBER PRIMARY KEY,
first_name VARCHAR2(50),
last_name VARCHAR2(50),
salary NUMBER
);

-- Inserting some records INSERT INTO employees VALUES (1,


'John', 'Doe', 50000);INSERT INTO employees VALUES (2, 'Jane',
'Smith', 60000);INSERT INTO employees VALUES (3, 'Bob',
'Johnson', 55000);

1. Using %TYPE Attribute

In this example, we have declared a


variable salary_var using %TYPE to match the data type of
the salary column in the employees table then we have assigned a value
to salary_var and displayed the assigned value
using DBMS_OUTPUT.PUT_LINE.

DECLARE
salary_var employees.salary%TYPE;BEGIN
-- Assign a value to the variable
salary_var := 70000;

-- Display the assigned value


DBMS_OUTPUT.PUT_LINE('Assigned Salary: ' || salary_var);END;

Output:
Explanation: In the above Query, We have declares a
variable salary_var with the same data type as the salary column in
the employees table, assigns a value of 70000 to it, and then prints the
assigned salary using DBMS_OUTPUT.PUT_LINE.

2. Using %ROWTYPE Attribute

In this example, we create a variable employee_record using %ROWTYPE,


which means it will have the same structure as a row in the employees table.
We then use a SELECT INTO statement to get data from the employees table
and store it in employee_record. Finally, we display the data using
DBMS_OUTPUT.PUT_LINE.

DECLARE
employee_record employees%ROWTYPE;BEGIN
-- Fetch data from the table into the record variable
SELECT * INTO employee_record FROM employees WHERE
employee_id = 2;

-- Display the retrieved data


DBMS_OUTPUT.PUT_LINE('Employee ID: ' ||
employee_record.employee_id);
DBMS_OUTPUT.PUT_LINE('First Name: ' ||
employee_record.first_name);
DBMS_OUTPUT.PUT_LINE('Last Name: ' ||
employee_record.last_name);
DBMS_OUTPUT.PUT_LINE('Salary: ' ||
employee_record.salary);END;

Output:

Explanation: In the above Query, We have declares a record


variable employee_record that matches the structure of
the employees table. It then fetches the data for the employee
with employee_id 2 into the employee_record variable using a
SELECT INTO statement and prints the retrieved data
using DBMS_OUTPUT.PUT_LINE.

Scalar Data Types in PL/SQL

Scalar data types are basic types that store only one value at a time.like
numbers, characters, or even logical values each representing an
individual value. The scalar data types are categorized into:
 Numeric Types: It Stores any integer value along with a fractional
entity whatever large it is or as per the requirement of the program.
 Character Types: Nodes represent strings of text and These act as
structures of text whereby an individual string is represented by a
node.
 Boolean Types: It Contains ‘true’ or ‘false’ values.
 Datetime Types: It is Used to represent date and time values which
are of typical usage in computer systems.

Subtypes are defined based on the base scalar types and are formed by
placing additional constraints upon values that can be assigned.

Numeric Data Types and Subtypes in PL/SQL


Numeric data types store numbers, both integers and real numbers, and
allow developers to perform arithmetic operations. The main numeric
types include:

 NUMBER: A highly flexible type that can store fixed-point or


floating-point numbers. It has precision and scale parameters. For
example, NUMBER(5, 2) can store up to 5 digits, with 2 of them
after the decimal point.
 BINARY_INTEGER/PLS_INTEGER: These types are used for
signed integers and are often faster than the generic NUMBER type
because they use machine-dependent formats.
 FLOAT: It is a subtype of NUMBER designed for storing floating-
point numbers. You can specify an optional precision such
as FLOAT(10) which allows for storing a number with up to 10
digits of precision

Character Data Types and Subtypes in PL/SQL


Character data types are designed to store any text, numbers or symbols
in the form of alphanumeric. They are used specifically for string
manipulation and are a vital part of PL/SQL.

 CHAR: It Handles variable-length binary data and fixed-length


character strings. If the string is less than the defined length, then the
rest is filled up with spaces. For instance, CHAR(10) would store
string as CHAR data type that has a length of 10 characters regardless
of the actual string length.
 VARCHAR2: To store character strings of varying
lengths. VARCHAR2 is slightly different because it only allocates
the required amount of space required to store the string. For
instance, VARCHAR2(10) data type can accommodate a string with
as many as 10 characters.

 LONG: It Can store variable-length character strings of up to 2


gigabytes. However, it is deprecated and it should be replaced
with CLOB to 2 GB. However, it is deprecated and should be
avoided in favor of CLOB.

Subtypes of Character Data Types

 STRING: A subtype of VARCHAR2, used to represent variable-


length strings.
 LONG VARCHAR: A deprecated subtype of VARCHAR2,
previously used to store large strings.

PL/SQL Boolean Data Types


The Boolean data type is unique to PL/SQL, allowing you to store
logical values and use them in conditional expressions.
BOOLEAN: This type can have three possible values: TRUE, FALSE,
or NULL. It is used in conditional statements and logical comparisons.
Notably, the BOOLEAN data type is unique to PL/SQL and cannot be
used in SQL statements directly.
PL/SQL Datetime and Interval Types
Datetime data types contain date and time and interval types contain the
difference between two datetime values. PL/SQL provides the following
datetime and interval types:
 DATE: It stores date and time values. These are the year, month,
day, hour, minute, and second as a part of the Date type.
 TIMESTAMP: It is an extension of the DATE data type with the
added feature of fractional seconds.
 TIMESTAMP WITH TIME ZONE: Saves a TIMESTAMP, but
with information about the time zone in which it has been set.
 TIMESTAMP WITH LOCAL TIME ZONE: Standalone function
that converts the TIMESTAMP to the time zone of the current
database session.
 INTERVAL YEAR TO MONTH: Saves the amount of time
measured in years and months.
 INTERVAL DAY TO SECOND: Saves as the time duration in
terms of days, hours, minutes, and seconds.
PL/SQL Large Object (LOB) Data Types
LOB data types store large amounts of unstructured data, such as text,
images, videos, and audio. PL/SQL provides several LOB types:
 BLOB(Binary Large Object): Stores binary large objects, such as
images or multimedia files.
 CLOB(Character Large Object): Stores large character data.
 NCLOB(National Character Large Object): Stores large character
data using the national character set.
 BFILE(Binary File): Stores a reference to a binary file stored outside
of the database.

PL/SQL Conditional Statements


PL/SQL (Procedural Language/Structured Query Language) is an
extension of SQL used in Oracle databases to write procedural code. It
includes various conditional statements that allow developers to execute
different blocks of code based on specific conditions. Decision-making
statements in programming languages decide the direction of the flow
of program execution. Conditional Statements available in PL/SQL are
defined below:
1. IF THEN
2. IF THEN ELSE
3. NESTED-IF-THEN
4. IF THEN ELSIF-THEN-ELSE Ladder

1. IF THEN

if then the statement is the most simple decision-making statement. It is


used to decide whether a certain statement or block of statements will be
executed or not i.e if a certain condition is true then a block of statement
is executed otherwise not.
Syntax:
if condition then
-- do something
end if;
Here, condition after evaluation will be either true or false. if statement
accepts boolean values – if the value is true then it will execute the
block of statements below it otherwise not. if and endif consider as a
block here.
Example:
declare-- declare the values here
begin
if condition thendbms_output.put_line('output');
end if;
dbms_output.put_line('output2');end;

-- pl/sql program to illustrate If statementdeclarenum1 number:=


10;num2 number:= 20;
begin
if num1 > num2 thendbms_output.put_line('num1 small');end if;
dbms_output.put_line('I am Not in if');
end;
As the condition present in the if statement is false. So, the block below
the if statement is not executed. Output:
I am Not in if
2. IF THEN ELSE
The if statement alone tells us that if a condition is true it will execute a
block of statements and if the condition is false it won’t. But what if we
want to do something else if the condition is false. Here comes the else
statement. We can use the else statement with if statement to execute a
block of code when the condition is false.
Syntax:-
if (condition) then
-- Executes this block if
-- condition is true
else
-- Executes this block if
-- condition is false

Example:-
-- pl/sql program to illustrate If else statementdeclarenum1 number:=
10;num2 number:= 20;
begin
if num1 < num2 thendbms_output.put_line('i am in if block');
ELSEdbms_output.put_line('i am in else Block');end if;
dbms_output.put_line('i am not in if or else Block');end;
Output:-
i'm in if Block
i'm not in if and not in else Block
The block of code following the else statement is executed as the
condition present in the if statement is false after calling the statement
which is not in block(without spaces).
3. NESTED-IF-THEN

A nested if-then is an if statement that is the target of another if


statement. Nested if-then statements mean an if statement inside another
if statement. Yes, PL/SQL allows us to nest if statements within if-then
statements. i.e, we can place an if then statement inside another if then
statement. Syntax:-
if (condition1) then
-- Executes when condition1 is true
if (condition2) then
-- Executes when condition2 is true
end if;
end if;

-- pl/sql program to illustrate nested If statementdeclarenum1 number:=


10;num2 number:= 20;num3 number:= 20;
beginif num1 < num2 thendbms_output.put_line('num1 small num2');
if num1 < num3 then dbms_output.put_line('num1 small num3 also');
end if;
end if;
dbms_output.put_line('after end if');end;
Output:-
num1 small num2
num1 small num3 also
after end if

4. IF THEN ELSIF-THEN-ELSE Ladder

Here, a user can decide among multiple options. The if then statements
are executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that if is
executed, and the rest of the ladder is bypassed. If none of the conditions
is true, then the final else statement will be executed. Syntax:-
if (condition) then
--statement
elsif (condition) then
--statement
.
.
else
--statement
endif
Flow Chart:-
Example:-
-- pl/sql program to illustrate if-then-elif-then-else ladderdeclarenum1
number:= 10;num2 number:= 20;
begin
if num1 < num2 thendbms_output.put_line('num1 small');
ELSEIF num1 = num2 thendbms_output.put_line('both equal');
ELSEdbms_output.put_line('num2 greater');end if;
dbms_output.put_line('after end if');end;
Output:-
num1 small
after end i
PL SQL Triggers:

PL/SQL triggers are stored programs that run automatically when a specific event
occurs in the database. They are created using the CREATE TRIGGER statement and can
be enabled or disabled. Triggers are defined on tables, views, schemas, or the
database and respond to DML, DDL, or system events. The two timing points are
BEFORE and AFTER the triggering event. They only affect new or changed data,
not existing data.

They are associated with response-based events such as a


 Database Definition Language statements such as CREATE, DROP or ALTER.
 Database Manipulation Language statements such as UPDATE, INSERT or DELETE.
 Database operations such as LOGON, LOGOFF, STARTUP, and SHUTDOWN .

PL/SQL Trigger

What is a Trigger in PL/SQL?

A trigger is something that automatically runs (or “fires”) when a specific event
happens in the database.

“Think of it like a security alarm: When someone opens a door (event), the alarm
goes off (trigger action).”

In databases, the event can be:

 INSERT (when someone adds data)


 UPDATE (when someone changes data), or
 DELETE (when someone removes data).

Why use triggers?

 To automatically check rules (e.g., don’t allow negative salary).


 To log changes (e.g., keep history of updates).
 To auto-update other tables when one changes.

Easy Example: Logging Employee Deletions


Let’s say we have two tables:

1.

employees – stores employee info.

employee_log – stores records of deleted employees (just for history).

We want: Every time an employee is deleted, the database should automatically add
their info to the employee_log table.

Code Example:
CREATE OR REPLACE TRIGGER trg_employee_delete
BEFORE DELETE ON employees
FOR EACH ROW
BEGIN
INSERT INTO employee_log(emp_id, emp_name, deleted_on)
VALUES (:OLD.emp_id, :OLD.emp_name, SYSDATE);
END;

Explanation:

 BEFORE DELETE ON employees: This trigger runs before a delete happens on the
employees table.
 :OLD is used to access the data before it gets deleted.
 SYSDATE adds the current date and time.
 So, when someone deletes a row from employees, this trigger automatically
copies that data into employee_log.

What is a Cursor?

In PL/SQL, a cursor is like a pointer that helps you go through rows of data one by
one from a query.

Think of it like:

You have a list of names. A cursor is your finger pointing at one name at a time as
you read them one by one.

Why use Cursors?


Normally, SQL works with entire sets of data at once. But sometimes you need to:

 Do something with each row separately, like print or process them.


 For that, we use a cursor to go through each row step-by-step.

Types of Cursors:

Implicit Cursor – Automatically used by PL/SQL when you write simple SQL
statements.

Explicit Cursor – You define it yourself when you want more control over how rows
are processed.

Example:

DECLARE

CURSOR c IS SELECT name FROM students;

v_name students.name%TYPE;

BEGIN

OPEN c;

FETCH c INTO v_name;

DBMS_OUTPUT.PUT_LINE('Student Name: ' || v_name);

CLOSE c;

END;

What this does:

 It selects the first student name from the students table,


 Stores it in v_name,
 And prints: Student Name: Arjun (or whatever the first name is).

What is Exception Handling?


Exception handling is used to catch and handle errors so your program doesn’t
crash.

Exception handling is used to catch and manage errors so that your program doesn't
crash when something goes wrong. It helps make your code more reliable, safe, and
user-friendly.

Think of it like:
“If something goes wrong, don’t panic — just do this instead.”

Example:

BEGIN

-- Trying to divide by zero (which causes an error)

DECLARE

a NUMBER := 10;

b NUMBER := 0;

c NUMBER;

BEGIN

c := a / b; -- This will cause an error

EXCEPTION

WHEN ZERO_DIVIDE THEN

DBMS_OUTPUT.PUT_LINE('Error: Cannot divide by zero!');

END;

END;

What’s happening:
 We’re trying to divide 10 by 0, which is not allowed.
 That causes a ZERO_DIVIDE error.
 Instead of crashing, the program catches the error and shows a friendly
message:
Error: Cannot divide by zero!

Reasons for Using Exception Handling:

 To prevent program crash – If an error happens (like divide by zero), the


program won’t stop suddenly.
 To show user-friendly messages – Instead of confusing error codes, you can
display clear messages like “Invalid input!” or “Data not found.”
 To handle unexpected situations smoothly – Like missing data, wrong input, or
file not found.
 To make debugging easier – You can log the exact error and fix it later.

You might also like