例外的概念和系统例外

例外

  • 例外是程序设计语言提供的一种功能,用来增强程序的健壮性和容错性。

ORACLE 中的例外

  • 系统例外

  • 自定义例外

系统例外

  • No_data_found (没有找到数据)
  • Too_many_rows (select..into语句匹配多个行)
  • Zero_Divide (被零除)
  • Value_error (算术或转换错误)
  • Timeout_on_resource (在等待资源时发生超时)

No_data_found 案例

--系统例外:no_data_found
SET SERVEROUTPUT ON

DECLARE
 pe_first_name EMPLOYEES.FIRST_NAME%TYPE;
 pe_last_name EMPLOYEES.LAST_NAME%TYPE;
 
BEGIN
 --查询员工号是1234的员工姓名
 select first_name,last_name into pe_first_name,pe_last_name from EMPLOYEES where EMPLOYEE_ID=1234;

exception
 when no_data_found then DBMS_OUTPUT.PUT_LINE('没有找到该员工');
 when others then DBMS_OUTPUT.PUT_LINE('其他例外');
end;
/
 

Too_many_rows 案例

--系统例外:too_many_rows
SET SERVEROUTPUT ON

DECLARE
 --定义变量
 pe_first_name EMPLOYEES.FIRST_NAME%TYPE;
 pe_last_name EMPLOYEES.LAST_NAME%TYPE;
 
BEGIN
 select first_name,last_name into pe_first_name,pe_last_name from EMPLOYEES where DEPARTMENT_ID=60;

exception
 when too_many_rows then DBMS_OUTPUT.PUT_LINE('selectinto 匹配了多行');
 
 when others then DBMS_OUTPUT.PUT_LINE('其他例外');
end;
/

Zero_Divide 案例

--系统例外:被0除 zero_divide
SET SERVEROUTPUT ON

DECLARE
 --定义变量
 pnum number;
 
BEGIN
 pnum := 1/0;
exception
 when zero_divide then DBMS_OUTPUT.PUT_LINE('1:0不能做除数');
                       DBMS_OUTPUT.PUT_LINE('2:0不能做除数');
 when others then DBMS_OUTPUT.PUT_LINE('其他例外');
end;
/
 

value_error 案例

--系统例外:value_error
SET SERVEROUTPUT ON

DECLARE
 --定义变量
 pnum number;
 
BEGIN
 pnum := 'abc';
exception
 when value_error then DBMS_OUTPUT.PUT_LINE('算术或者转换错误');
 when others then DBMS_OUTPUT.PUT_LINE('其他例外');
end;
/
 

自定义例外

  • 定义变量,类型是exception
  • 使用raise抛出自定义例外
--自定义例外:查询50号部门的员工的姓名
SET SERVEROUTPUT ON

DECLARE
 --定义光标,代表50号部门的员工姓名
 cursor cemp is select first_name,last_name from EMPLOYEES where DEPARTMENT_ID = 300;
 
 pe_first_name EMPLOYEES.first_name%type;
 pe_last_name EMPLOYEES.LAST_NAME%TYPE;
 
 --自定义例外
 no_emp_found EXCEPTION;
BEGIN
 --打开光标
 open cemp;
 
 --直接取一个员工的姓名
 FETCH cemp into pe_first_name,pe_last_name;
 
 if cemp%notfound then
    --抛出例外
    raise no_emp_found;
 end if;
  
 --关闭光标
 --oracle会自动启动pmon(process monitor) 关闭光标
 close cemp;
exception
 when no_emp_found then DBMS_OUTPUT.PUT_LINE('没有找到员工');
 when others then DBMS_OUTPUT.PUT_LINE('其他例外');
end;
/
 
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容