How are exceptions handled in PL/SQL (predefined, user-defined)?
Jun 12, 2025 am 10:23 AMIn PL/SQL, exceptions are categorized into two types: predefined and user-defined. 1. Predefined exceptions are built-in errors such as NO_DATA_FOUND, TOO_MANY_ROWS, VALUE_ERROR, ZERO_DIVIDE, and INVALID_NUMBER, which are automatically raised during specific runtime errors. 2. User-defined exceptions allow developers to manually declare, raise, and handle custom errors using the DECLARE section, RAISE statement, and EXCEPTION block. Additionally, best practices include avoiding empty handlers, using WHEN OTHERS cautiously, logging meaningful messages, and limiting unnecessary custom exceptions to ensure clean, maintainable error handling in PL/SQL programs.
In PL/SQL, exceptions are used to handle runtime errors so that a program can continue running or terminate gracefully. These exceptions can either be predefined (like NO_DATA_FOUND) or user-defined (custom exceptions created by the developer). Knowing how both types work and when to use them is key to writing robust PL/SQL code.
Predefined Exceptions: Built-in Errors You Should Know
Oracle has a set of predefined exceptions that are automatically raised when specific database errors occur. These are the most commonly used and recognized exceptions in PL/SQL.
Some of the more frequently encountered ones include:
-
NO_DATA_FOUND
: Raised when aSELECT INTO
statement returns no rows. -
TOO_MANY_ROWS
: Raised when aSELECT INTO
returns more than one row. -
VALUE_ERROR
: Happens when an arithmetic, conversion, truncation, or size constraint error occurs. -
ZERO_DIVIDE
: When division by zero happens. -
INVALID_NUMBER
: When converting a string to a number fails due to invalid input.
Here’s how you’d typically catch a predefined exception:
BEGIN SELECT salary INTO v_salary FROM employees WHERE employee_id = 9999; EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE('No employee found with that ID.'); END;
You don’t need to declare these exceptions — they’re already known to PL/SQL. Just reference them in your EXCEPTION
block.
User-Defined Exceptions: When You Need More Control
Sometimes, predefined exceptions aren’t enough. That’s where user-defined exceptions come in handy. You can define your own exceptions for situations that aren’t covered by Oracle's built-in list.
The process involves three steps:
- Declaration — Declare your exception in the DECLARE section.
- Raising — Use the
RAISE
statement to trigger it manually. - Handling — Catch it in the EXCEPTION block like any other.
For example:
DECLARE invalid_salary EXCEPTION; v_salary NUMBER := -5000; BEGIN IF v_salary < 0 THEN RAISE invalid_salary; END IF; EXCEPTION WHEN invalid_salary THEN DBMS_OUTPUT.PUT_LINE('Salary cannot be negative.'); END;
This gives you control over what constitutes an error in your logic. You can also associate user-defined exceptions with error codes using PRAGMA EXCEPTION_INIT
, which lets you link them to specific Oracle error numbers if needed.
Best Practices for Exception Handling
When working with exceptions in PL/SQL, there are a few important things to keep in mind:
- Avoid empty exception handlers: Swallowing exceptions without logging or handling them can hide bugs.
-
Use WHEN OTHERS carefully: It catches all unhandled exceptions, but should usually end with a
RAISE
or logging mechanism. - Log meaningful messages: Help future developers (including yourself) understand what went wrong.
- Don’t overuse user-defined exceptions: Only create custom exceptions when they truly add clarity or control.
Also, remember that exception blocks are executed only when an error occurs, so avoid putting regular logic inside them unless necessary.
Wrapping Up
Handling exceptions in PL/SQL boils down to understanding two main types — predefined and user-defined — and knowing when and how to use each. While Oracle provides many built-in exceptions for common database issues, defining your own can help manage application-specific logic errors. Either way, good exception handling makes your programs more reliable and easier to debug.
That's basically it — not overly complicated, but easy to overlook some details if you're not careful.
The above is the detailed content of How are exceptions handled in PL/SQL (predefined, user-defined)?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The logical structure of Oracle database focuses on how data is organized by users and developers, including tables, views, patterns and table spaces; the physical structure involves the actual storage of data on disk, including data files, redo logs, control files, etc. 1. The logical structure includes tables, views, indexes, patterns and table spaces, which determine how users access data; 2. The physical structure consists of data files, redo logs, control files and archive logs, which are responsible for the persistence and recovery of data; 3. The table space is a key bridge connecting logic and physics, and its capacity is limited by the underlying data files; 4. Different roles have different levels of attention, developers focus on logic optimization, and DBA pays more attention to physical management; 5. Understanding the differences between the two can help efficiently troubleshoot problems, optimize performance and reasonable management

PL/SQLextendsSQLwithproceduralfeaturesbyaddingvariables,controlstructures,errorhandling,andmodularcode.1.Itallowsdeveloperstowritecomplexlogiclikeloopsandconditionalswithinthedatabase.2.PL/SQLenablesthedeclarationofvariablesandconstantsforstoringinte

AutomaticStorageManagement(ASM)isOracle’sbuilt-instoragesolutiondesignedtosimplifyandoptimizethemanagementofdatabasestorage.1.IteliminatestheneedforexternalvolumemanagersorRAIDconfigurations.2.ASMautomaticallybalancesI/Oacrossdisks,preventinghotspots

OracleDataGuard supports three standby databases: physical, logical, and snapshot. 1. The physical standby database is a byte-level copy of the main library, synchronized using RedoApply, suitable for disaster recovery; 2. The logical standby database applies changes through SQLApply, which can be structured different from the main library, suitable for reporting and selective replication; 3. The snapshot standby database is based on physical standby and can be converted into a writable state for testing, and FlashbackDatabase needs to be enabled. Select according to requirements: requires data consistency and quick switching of physics, requires flexibility and support for report selection logic, and select snapshots if you need to test the production environment copy.

InPL/SQL,exceptionsarecategorizedintotwotypes:predefinedanduser-defined.1.Predefinedexceptionsarebuilt-inerrorssuchasNO_DATA_FOUND,TOO_MANY_ROWS,VALUE_ERROR,ZERO_DIVIDE,andINVALID_NUMBER,whichareautomaticallyraisedduringspecificruntimeerrors.2.User-d

SubqueriesinOracleSQL—scalar,multi-row,andcorrelated—enhancequeryflexibilitybyenablingmodularlogic,dynamicdatahandling,andcomplexfiltering.Scalarsubqueriesreturnasinglevalueandareidealforcomparisonsorexpressionssuchascomputingtheaveragesalary;1.theys

Oracle sequences are independent database objects used to generate unique values ??across sessions and transactions, often used for primary keys or unique identifiers. Its core mechanism is to generate a unique value through NEXTVAL increment, and CURRVAL obtains the current value without incrementing. Sequences do not depend on tables or columns, and support custom start values, step sizes and loop behaviors. Common scenarios during use include: 1. Primary key generation; 2. Order number; 3. Batch task ID; 4. Temporary unique ID. Notes include: transaction rollback causes gaps, cache size affects availability, naming specifications and permission control. Compared to UUID or identity columns, sequences are suitable for high concurrency environments, but they need to be traded down based on the needs.

In Oracle, the schema is closely associated with the user account. When creating a user, the same-name mode will be automatically created and all database objects in that mode are owned. 1. When creating a user such as CREATEUSERjohn, create a schema named john at the same time; 2. The tables created by the user belong to their schema by default, such as john.employees; 3. Other users need authorization to access objects in other schemas, such as GRANTSELECTONsarah.departmentsTOjohn; 4. The schema provides logical separation, used to organize data from different departments or application modules.
