The Wayback Machine - https://web.archive.org/web/20241001135834/https://www.geeksforgeeks.org/plsql-raise-exceptions/
Open In App

PL/SQL RAISE Exceptions

Last Updated : 16 Feb, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

PL/SQL stands for Procedural Language Extension to the Structured Query Language and it is designed specifically for Oracle databases. It extends Structured Query Language (SQL) capabilities by allowing the creation of stored procedures, functions, and triggers. It is a block-structured language that combines SQL with the procedural features of programming languages. In this article, we will learn about RAISE Exception in PL/SQL with its syntax, types, and examples.

How to Raise Exceptions in PL/SQL?

PL/SQL Raise Exception is a feature that helps us to handle errors in a structured and efficient manner. Exceptions in PL/SQL are used to manage unexpected situations and ensure the integrity of the database. There are three ways to Raise an exception in PL/SQL.

  1. User-Defined Exception.
  2. Internally Defined Exception.
  3. Current Exception.

Syntax:

DECLARE
custom_exception EXCEPTION;
BEGIN
-- Some condition that may warrant raising a user-defined exception
IF some_condition THEN
-- Raise a user-defined exception
RAISE custom_exception;
END IF;

-- Rest of the code...

EXCEPTION
WHEN custom_exception THEN
-- Handle the user-defined exception
DBMS_OUTPUT.PUT_LINE('Custom exception handled!');
END;

Explanation:

  • if some_condition is true then the RAISE custom_exception statement will be executed and make happen the user-defined exception custom_exception to be raised.
  • The WHEN custom_exception THEN block in the EXCEPTION section will catch and handle this exception.

1. User-Defined Exception

It is a type of exception that is defined by a developer to handle specific error conditions or business rules in their PL/SQL code. we can declare a user-defined exception using the EXCEPTION keyword and we can raise it using the RAISE statement.

Example:

DECLARE
custom_exception EXCEPTION;
BEGIN
IF true THEN
-- If a specific condition is met, raise the user-defined exception
RAISE custom_exception;
END IF;
EXCEPTION
WHEN custom_exception THEN
DBMS_OUTPUT.PUT_LINE('Custom exception handled!');
END;

Output:

Statement processed.
Custom exception handled!

Explanation: In the above query we have declares a custom exception custom_exception. If a condition (in this case, always true for demonstration purposes) is met then it raises the custom_exception. The EXCEPTION block catches and handles the custom_exception, printing ‘Custom exception handled!‘ using DBMS_OUTPUT.PUT_LINE.

2. Internally Defined Exception

It is type of exception that are predefined by the PL/SQL runtime environment to handle common error conditions which occur during program execution. It includes exception such as NO_DATA_FOUND, TOO_MANY_ROWS, ZERO_DIVIDE, DUP_VAL_ON_INDEX, STORAGE_ERROR etc.

Example:

DECLARE
result NUMBER;
BEGIN
-- Some computation that might cause an internally defined exception
result := 10 / 0; -- This will raise ZERO_DIVIDE exception
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('Cannot divide by zero!');
END;

Output:

Statement processed.
Cannot divide by zero!

Explanation: In the above query we computes a division operation (10 / 0) which causes a division by zero error and leading to the ZERO_DIVIDE exception being raised. The EXCEPTION block catches and handles this exception by printing ‘Cannot divide by zero!‘ using DBMS_OUTPUT.PUT_LINE.

3. Current Exception

It is a type of exception that is currently being handled in the PL/SQL block. It is useful in nested blocks where an exception might be raised in an inner block and you want to reference that specific exception in an outer block. SQLERRM function is used to refer current exception.

Example:

DECLARE
custom_exception EXCEPTION;
BEGIN
BEGIN
-- Some operation that might raise an exception
RAISE custom_exception;
EXCEPTION
WHEN OTHERS THEN
-- Handle the exception and reference the current exception
DBMS_OUTPUT.PUT_LINE('Exception handled: ' || SQLERRM);
END;
END;

Output:

Statement processed.
Exception handled: User-Defined Exception

Explanation: In the above query we demonstrates nested exception handling. It raises a user-defined exception (custom_exception) within an inner block. The EXCEPTION block in the outer block catches any exceptions (including the custom_exception) using WHEN OTHERS and prints the error message (SQLERRM) to the console.

Examples of PL/SQL Raise Exception

The below example is demonstrating the use of user-defined exceptions in a real-world scenario. It illustrates how to create a table, a PL/SQL procedure, and handle exceptions related to a specific business rule (salary limit).

Step 1: Create a employee table

CREATE TABLE employee (
emp_id NUMBER PRIMARY KEY,
emp_name VARCHAR2(50),
emp_salary NUMBER
);

Step 2: Create a Procedure with an Exception

CREATE OR REPLACE PROCEDURE insert_employee(
p_emp_id NUMBER,
p_emp_name VARCHAR2,
p_emp_salary NUMBER
)
IS
emp_salary_limit EXCEPTION;
BEGIN
-- Check if the salary is within the allowed limit
IF p_emp_salary > 100000 THEN
-- If not, raise a user-defined exception
RAISE emp_salary_limit;
ELSE
-- Insert the employee details into the table
INSERT INTO employee(emp_id, emp_name, emp_salary)
VALUES (p_emp_id, p_emp_name, p_emp_salary);

DBMS_OUTPUT.PUT_LINE('Employee inserted successfully.');
END IF;
EXCEPTION
WHEN emp_salary_limit THEN
-- Handle the user-defined exception
DBMS_OUTPUT.PUT_LINE('Error: Employee salary exceeds the allowed limit.');
END;

This procedure will check if the p_emp_salary is greater then 100000 then it will raise a user-defined exception(emp_salary_limit) else it will insert a new record into a employee table.

Step 3: Run the Procedure

DECLARE
emp_id_param NUMBER := 101;
emp_name_param VARCHAR2(50) := 'John Doe';
emp_salary_param NUMBER := 120000;
BEGIN
insert_employee(emp_id_param, emp_name_param, emp_salary_param);
END;

Output:

Statement processed. high salary
Error: Employee salary exceeds the allowed limit.

Now trying to insert new record with low salary.

DECLARE
emp_id_param NUMBER := 101;
emp_name_param VARCHAR2(50) := 'John Doe';
emp_salary_param NUMBER := 10000;
BEGIN
insert_employee(emp_id_param, emp_name_param, emp_salary_param);
END;

Output:

Statement processed.
Employee inserted successfully.

Conclusion

Pl/SQL is a Procedural Language that is used to write program blocks, procedures, functions, cursors, triggers for databases. It provides a Raise exception feature that is used to handle errors in a structured and efficient manner. You can use predefined exceptions, custom exceptions, or referring to the current exception to ensure the code handles unexpected situations.



Similar Reads

SQL Exercises : SQL Practice with Solution for Beginners and Experienced
SQL (Structured Query Language) is a powerful tool used for managing and manipulating relational databases. Whether we are beginners or experienced professionals, practicing SQL exercises is important for improving your skills. Regular practice helps you get better at using SQL and boosts your confidence in handling different database tasks. So, in
15+ min read
SQL Cheat Sheet ( Basic to Advanced)
Creating and managing databases in SQL involves various commands and concepts that handle the structuring, querying, and manipulation of data. In this guide, we will see a comprehensive cheat sheet for essential SQL operations, offering a practical reference for tasks ranging from database creation to advanced data handling techniques. It includes
15 min read
MySQL Tutorial
This MySQL Tutorial is made for both beginners and experienced professionals. Whether you're starting with MYSQL basics or diving into advanced concepts, this free tutorial is the ideal guide to help you learn and understand MYSQL, no matter your skill level. From setting up your database to performing complex queries and database administration ta
11 min read
How to Design ER Diagram for a Hospital Management System
Healthcare management is a crucial function that comes as the backbone of hospital management. An ER (Entity-Relationship) Diagram therefore functions as a foundation for the organization and visualization of the various entities, attributes, and relationships within a system. In this article, the steps of building an ER Diagram for a Hospital Mana
7 min read
SQL Tutorial
In this SQL tutorial, you’ll learn all the basic to advanced SQL concepts like SQL queries, SQL join, SQL injection, SQL insert, and creating tables in SQL. SQL is easy to learn, there are no prerequisites to learn SQL. So, SQL is a standard database language used to access and manipulate data in databases. SQL stands for Structured Query Language.
11 min read
SQL Query Interview Questions
SQL or Structured Query Language is a standard language for relational databases. SQL queries are powerful tools used to, manipulate, and manage data stored in these databases like MySQL, Oracle, PostgreSQL, etc. Whether you're fetching specific data points, performing complex analyses, or modifying database structures, SQL queries provide a standa
10 min read
Rank and Dense Rank in SQL Server
The RANK() and DENSE_RANK() functions are essential tools in SQL Server for assigning rankings to rows in a dataset based on specified criteria. RANK() functions assign a unique rank to each distinct row in the result set, with tied rows receiving the same rank and leaving gaps in subsequent ranks. For example, if two rows tie for first place, the
7 min read
MySQL Interview Questions
MySQL is a Free open-source Relational Database Management System(RDMS) that stores data in a structured tabular format using rows and columns. It uses Structured Query Language (SQL) for accessing, managing, and manipulating databases. It was originally developed by MySQL AB, a Swedish company, and is now owned by Oracle Corporation. It's known fo
13 min read
Database Schemas
Nowadays data is one of the most important things in the business world, every business captures its customers data to understand their behavior, in the world of the internet, data is growing like crazy, so businesses need more advanced database solutions by which they can maintain the database systems and whenever they need data to solve business
8 min read
MongoDB Tutorial
In today's data-driven world, the ability to efficiently store and manage large amounts of data is crucial. MongoDB, a powerful NoSQL database, has become a go-to choice for developers looking for flexibility, scalability, and performance. Unlike traditional relational databases, MongoDB uses a document-oriented data model, making it easier to hand
10 min read
30 Days of SQL - From Basic to Advanced Level
This basic to advanced SQL tutorial covers the entire SQL syllabus in a structured way and provides the best learning material and strategies to master complete SQL in 30 Days. We have laid out the complete SQL roadmap, and following this roadmap, you will learn all the concepts of SQL. All Important concepts in the SQL syllabus like SQL queries, s
8 min read
Window functions in SQL
Window functions apply to aggregate and ranking functions over a particular window (set of rows). OVER clause is used with window functions to define that window. OVER clause does two things : Partitions rows to form a set of rows. (PARTITION BY clause is used) Orders rows within those partitions into a particular order. (ORDER BY clause is used) N
4 min read
Introduction to NoSQL
NoSQL is a type of database management system (DBMS) that is designed to handle and store large volumes of unstructured and semi-structured data. Unlike traditional relational databases that use tables with pre-defined schemas to store data, NoSQL databases use flexible data models that can adapt to changes in data structures and are capable of sca
10 min read
SQL Trigger | Student Database
A trigger is a stored procedure in a database that automatically invokes whenever a special event in the database occurs. For example, a trigger can be invoked when a row is inserted into a specified table or when specific table columns are updated. In simple words, a trigger is a collection of SQL statements with particular names that are stored i
7 min read
CTE in SQL
The Common Table Expressions (CTE) were introduced into standard SQL in order to simplify various classes of SQL Queries for which a derived table was just unsuitable. CTE was introduced in SQL Server 2005, the common table expression (CTE) is a temporary named result set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement.
6 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands
SQL commands are extensively used to interact with databases, enabling users to perform a wide range of actions on database systems. Understanding these commands is crucial for effectively managing and manipulating data. This guide will introduce you to the various SQL sublanguage commands, including Data Definition Language (DDL), Data Query Langu
6 min read
SQL | Subquery
In SQL a Subquery can be simply defined as a query within another query. In other words we can say that a Subquery is a query that is embedded in WHERE clause of another SQL query. Important rules for Subqueries: You can place the Subquery in a number of SQL clauses: WHERE clause, HAVING clause, FROM clause. Subqueries can be used with SELECT, UPDA
3 min read
How to find Nth highest salary from a table?
Structured Query Language is a computer language that we use to interact with a relational database. Finding Nth highest salary in a table is the most common question asked in interviews. Here is a way to do this task using the dense_rank() function. Consider the following table: Employee: CREATE TABLE: CREATE TABLE emp ( emp_name VARCHAR(50), emp_
4 min read
ALTER (RENAME) in SQL
Sometimes we may want to rename our table to give it a more relevant name. For this purpose, we can use ALTER TABLE to rename the name of the table. SQL ALTER TABLE is a command used to modify the structure of an existing table in a database. Here we will discuss Alter Command in SQL in detail. Alter in SQLHere we are discussing the syntax of Alter
2 min read
SQL | WITH Clause
The SQL WITH clause, also known as Common Table Expressions (CTEs), was introduced by Oracle in the Oracle 9i release 2 database. The SQL WITH clause allows you to give a sub-query block a name (a process also called sub-query refactoring), which can be referenced in several places within the main SQL query.  What is the SQL WITH Clause?The clause
3 min read
SQL Interview Questions
SQL is a standard database language used for accessing and manipulating data in databases. It stands for Structured Query Language and was developed by IBM Computer Scientists in the 1970s. By executing queries, SQL can create, update, delete, and retrieve data in databases like MySQL, Oracle, PostgreSQL, etc. Overall, SQL is a query language that
15+ min read
SQL Date and Time Functions
In SQL, dates are complicated for newbies, since while working with a database, the format of the data in the table must be matched with the input data to insert. In various scenarios instead of date, datetime (time is also involved with date) is used. For storing a date or a date and time value in a database,MySQL offers the following data types:
3 min read
SQL Views
Views in SQL are a kind of virtual table. A view also has rows and columns like tables, but a view doesn't store data on the disk like a table. View defines a customized query that retrieves data from one or more tables, and represents the data as if it was coming from a single source. We can create a view by selecting fields from one or more table
8 min read
SQL | GROUP BY
The GROUP BY Statement in SQL is used to arrange identical data into groups with the help of some functions. i.e. if a particular column has the same values in different rows then it will arrange these rows in a group.  FeaturesGROUP BY clause is used with the SELECT statement.In the query, the GROUP BY clause is placed after the WHERE clause.In th
4 min read
SQL CREATE TABLE
CREATE TABLE command creates a new table in the database in SQL. In this article, we will learn about CREATE TABLE in SQL with examples and syntax. SQL CREATE TABLE StatementSQL CREATE TABLE Statement is used to create a new table in a database. Users can define the table structure by specifying the column's name and data type in the CREATE TABLE c
3 min read
SQL Joins (Inner, Left, Right and Full Join)
SQL Join operation combines data or rows from two or more tables based on a common field between them. In this article, we will learn about Joins in SQL, covering JOIN types, syntax, and examples. SQL JOINSQL JOIN clause is used to query and access data from multiple tables by establishing logical relationships between them. It can access data from
5 min read
SQL UPDATE Statement
SQL UPDATE Statement modifies the existing data from the table. UPDATE Statement in SQL The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using the UPDATE statement as per our requirement. In a very simple way, we can say that SQL commands(UPDATE and
3 min read
SQL SELECT Query
The SQL SELECT Statement retrieves data from a database. SELECT Statement in SQLThe SELECT statement in SQL is used to fetch or retrieve data from a database. It allows users to access the data and retrieve specific data based on specific conditions. We can fetch either the entire table or according to some specified rules. The data returned is sto
3 min read
SQL Aggregate functions
SQL Aggregate functions are functions where the values of multiple rows are grouped as input on certain criteria to form a single value result of more significant meaning. It is used to summarize data, by combining multiple values to form a single result. SQL Aggregate functions are mostly used with the GROUP BY clause of the SELECT statement. Vari
2 min read
SQL Query to Find Second Highest Salary
There are a lot of real-world scenarios where a query for finding the nth salary will be really useful. Considering finding the second-highest salary in SQL, we have one sample table. Finding Second Highest SalaryConsider below simple table: Name Salary Aman100000Shubham1000000Naveen 40000Nishant500000How to find the employee whose salary is the se
3 min read
Article Tags :