Oracle數據庫——PL/SQL程序設計(例外)

例外是程序設計語言提供的一種功能,用來增強程序的健壯性和容錯性。

Oracle中的例外

1、系統例外

(1)Timeout_on_resource(在等待資源時發生超時)

在這裏插入圖片描述

(2)No_data_found (沒有找到數據)

--系統例外: no data found
set serveroutput on
declare
	pename emp.ename%type;
begin
	--查詢員工號是1234的員工姓名
	select ename into pename from emp where empno = 1234;
	exception
		when no_data_found then dbms_output.put_line( '沒有找到該員工') ;
		when others then dbms_output.put_line( '其他例外');
end;
/

在這裏插入圖片描述

(3)Too_many_rows (select …into語句匹配多個行)

--系統例外: too many_ rows
set serveroutput on
declare
	pename emp.ename%type;
begin
	--查詢所有10號部門的員工姓名
	select ename into pename from emp where deptno = 10;
	exception
		when too_many_rows then dbms_output.put_line( 'select into 匹配了多行') ;
		when others then dbms_output.put_line( '其他例外');
end;
/

在這裏插入圖片描述

(4)Zero_Divide (被零除)

--系統例外:被零除zero_ divide
set serveroutput on
declare
	--定義一個基本變量
	pnum number;
begin
	pnum := 1/0;
	exception
		when zero_divide then dbms_output.put_line('l: 0不能做除數');
							  dbms_output.put_line('2: 0不能做除數');
		when others then dbms_output.put_line( '其他例外') ;
end;
/

在這裏插入圖片描述

(5)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;
/

在這裏插入圖片描述

2、自定義例外

定義變量,類型是exception

使用raise拋出自定義例外

--自定義例外:查詢50號部門的員工姓名
set serveroutput on
declare
	--定義光標,代表50號部門的員工姓名
	cursor cemp is select ename from emp where deptno = 50;
	pename emp.ename%type;
	no_emp_found exception;
begin
	open cemp;
	fetch cemp into pename;
	if cemp%notfound then
		raise no_emp_found;
	end if ;
close cemp;
exception
	when no_emp_found then dbms_output.put_line('沒有找到員工');
	when others then dbms_output.put_line('其他例外');
end;
/

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章