Exception Handling in SQL Server by TRY CATCH Method


Exception Handling in SQL Server – Table of Content

Introduction to Exception handling in SQL server:

An Exception is nothing but an error mechanism that occurs in any program during the time of program execution.The methods used to resolve these errors are called Exception handling. Now Exception handling methods are widely used in the SQL Server because it’s easy to use methodology.There are several Exception handling available in SQL servers such as TRY and CATCH methods.We will be going to explain these sections later. SQL server 2005 has introduced the new Exception handling methods to help programs to run effortlessly and error-free. Sometimes it difficult to capture the errors which occurred during the time of end programming execution. Even user needs to know these kinds of mistakes happened in the end-users with programming codes.

To gain in-depth knowledge with practical experience in SQL server, then explore  SQL server Training!

TRY and CATCH methods:

SQL server 2005 has introduced these two methods to handle exceptions, such as TRY and CATCH. Both these TRY and CATCH statements work similarly to any other programming language. First, this statement is executed in the SQL server statement, which the user has written in the TRY block. If the Error occurred again, then TRY will automatically get executed the CATCH block.

EXAMPLE:

BEGIN TRY # executing first the TRY statement
// now insert the SQL statements
END TRY # ending of TRY statement
Now it’s time to execute the CATCH statement
BEGIN CATCH # executing the CATCH statement
// now this statement handle the exception details
END CATCH # ending of CATCH statement
The following are the numbers of Error handling property statements in the TRY…CATCH statements;
ERROR_NUMBER () # handling the Error in NUMBER property
ERROR_STATE () # handling the Error in STATE property
ERROR_SEVERITY () # handling the SEVERITY errors
ERROR_LINE () # handling the errors in LINE property
ERROR_PROCEDURE () # handling the PROCEDURAL errors
ERROR_MESSAGE () # handling the Message errors

NOTE: Normally, SQL Server stores the Error as a message; this Error has occurred in the execution of the following statement table;
Select * from sys.messages

HANDLING EXCEPTION using TRY AND CATCH statements:

In this section, I am going to explain the steps involved in handling the Exception using TRY and CATCH statements,

Steps:

Step1: user need to create the Custom error table with the name “Error Tracer,”

Step2: user needs to write the common stored procedure for handling the current Exception in the table name Proc_InsertErrorDetails, which helps the user insert the error details into the given step1 created table already.

Step3: Now, need to write a simple procedure and execute the exception handling statement using TRY……CATCH. When you get the errors, it will automatically call the Procs_InsertErrorDeatils and inserts the Error details.

Step4: Now, it’s time to check the ErrorTracer table that will list out all the occurred error details.

Programming example:

USE [Northwind] #create the NorthWind table 
GO
IF OBJECT_ID (‘databaseobject.ErrorTarcer’) IS NOT NULL value
BEGIN
DROP TABLE database object.ErrorTracer
PRINT ‘Table database object.ErrorTarcer Dropped’
END
GO

CREATE TABLE ErrorTracer
(
…………………
…………………# inserting table values
…………………..
)

IF OBJECT_ID (‘Proc_InsertErrorDetails’) IS NOT NULL

BEGIN
DROP PROCEDURE [databaseobject]. [Proc_InsertErrorDetails]
PRINT ‘procedure Proc_InsertErrorDetails Dropped’
END
GO

Syntax of Exception Handling:

TRY BLOCK
SET of SQL Statement
Throws error
> CATCH BLOCKS
Handling Exception
(Error log, Rollback)
The code is as follows;
/* SQL statements*/
END TRY #end of the try statement
BEGIN CATCH # start of the BEGIN statement
Print ERROR OR
ROLLBACK Transaction
END CATCH

In this Exception handling, SQL statements were inserted into try Blocks. If all the inserted statements were executed without any error, then the try statement ‘OK’ will go to the CATCH Block.

Types of SQL server Exceptions:

There are two types of SQL server Exceptions available; such as

  • System defined Exception handling
  • User-defined Exception handling

 Let us discuss them one by one,

System defined Exception handling:

The system defined Exception handling is the system generates nothing but Exceptions.

Example:

Declare @Valu1 int;
Declare @Valu2 int;
BEGIN TRY
Set @Valu1 = 9;
Set @Valu2 = @Valu1/0; /*Error has occurred */
END TRY
BEGIN CATCH
Print ‘An error occurred:’
Print Error_Message () /* property of exception handling
END CATCH

OUTPUT:
An Error Occurred
Divided by Zero error encountered

User-Defined Exception handling:

This type of Exception is generated by the users, not by any system.

SQL Server Certification Training

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

Programming example:

Declare @valu1 int;
Declare @valu2 int;
BEGIN TRY
Set @valu1 = 9;
Set @Valu2 = @Valu1 % 2;
If @Valu1 = 1
Print ‘Error Not occurred’
Else
BEGIN
Print ‘Error Occurs’;
Throw 80000, ‘Number is even’, 5
End

END TRY
BEGIN CATCH
Print ‘Error occurs that is: ‘
Print Error_Message ()
END CATCH

Output:

Error occurs
The Error occurs that is:
Number is even

Here 80000 denote the error number, and 5 represents the state where the error message has occurred.

System functions and keywords used within the CATCH block:

Now we are going to explain the few programming examples to define these functions and system keyword;
First, we need to create a table and enter some value into the table as follow;

CREATE TABLE emp
(
Emp_ID int Identify (1,1),
First_name Nvarchar (MAX) not Nullval,
Last_name Nvarchar (MAX) not Nullval,
Salary Int Not Null check (Salary > 20,000),
City Nvarchar (max) Not Nullval
)
Insert data into the table values;
Select ‘Kavya,’ ‘Gowda,’ 50000, ‘Alwar’ Union ALL
Select ‘Rahul,’ ‘chowdary,’ 25000, ‘Alwar’ Union ALL
Select ‘Sandeep,’ ‘Prajapati,’ 23000, ‘Alwar’ Union ALL
Select ‘Sanjeev,’ ‘Jangid,’ 27000, ‘Alwar’ Union ALL
Select ‘Neeraj,’ ‘Baldia,’ 24000, ‘Alwar’ Union ALL
Select ‘Narendra,’ ‘Saini,’ 22000, ‘Alwar’ Union ALL
è Now it’s time to execute the ‘SELECT’ statements by using the command,
Select * from Employee
Serl.no
Emp_id
First_name
Last_name
Salary
City

1
1
Kavya
Gowda
50000
Alwar

2
2
Rahul
Chowdary
25000
Alwar

3
3
Sandeep
Prajapat
23000
Alwar

4
4
Sanjeev
Jangid
27000
Alwar

5
5
Neeraj
Baldia
24000
Alwar

6
6
Narendra
Saini
22000
Alwar

Exception handling properties:

Example1: @ERROR;

This statement returns the error number for the last executed SQL statements. It returns zero if the previous transaction SQL statements were encountered, and it will not return an error number.

UPDATE Employee SET Salary = 20000 WHERE Emp_ID = 5
IF @ERROR = 547
PRINT ‘A check constraints violation error occurred. ‘;

Output:
Msg 557, level 14, State 0, Line 1

The UPDATE statement conflicted with the method CHECK constraint ‘CK_Employee_salary_68487DD7’.

Example 2: ERROR_NUMBER

This Exception handling property returns the number values which causes the errors. It would replace the ZERO if we called outside the CATCH block statement.

BEGIN TRY
UPDATE Employee SET salary_val = 20000 WHERE Emp_ID = 6
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER () AS errorNumber;
END CATCH;

OUTPUT:
ERRORNUMBER = 557

Example 3:

ERROR_MESSAGE returns the errors which are caused by the messages. This returns the type of ERROR_MESSAGE is the type of nvarchar (5000).

BEGIN TRY
UPDATE Employee SET Salary =20000 WHERE EMP_ID = 6
END TRY
BEGIN CATCH
SELECT ERROR_MESSAGE () AS ERRORMSG;

END CATCH;

OUTPUT:
The UPDATE statement conflict the CHECK Constraint ‘CK_EMPLOYEE_SALARY_68487DD7’. This conflict method will be stored in HOME_MANAGMENT.

EXAMPLE 4: ERROR_STATE

ERROR_STATE returns the number of state errors. The data type of ERROR_STATE is Integer.

BEGIN TRY
SELECT SALARY+ FIRST _NAME from EMPLOYEE WHERE Emp_ID = 6
END TRY
BEGIN CATCH
SELECT ERROR_STATE () AS ERRORState, ERROR_MESSAGE () ErrorMSG;
END CATCH;

OUTPUT:

ErrorState = 1
ErrorMsg = Conversion failed error message where it returns the value in Nvarchar.

Example 5: ERROR_LINE

ERROR_LINE exception handling returns the line number where the Error has occurred. The return type of ERROR_LINE is Integer.

BEGIN TRY
SELECT SALARY + First_name from Employee WHERE EMP_ID = 6
END TRY
BEGIN CATCH
SELECT ERROR_STATE () As ErrorLine;
END CATCH;

OUTPUT:
ErrorLine = 1

Example 6: ERROR_PROCEDURE

ERROR_PROCEDURE returned the name of the stored triggers and procedure when an error occurred. The return type is ERROR_PROCEDURE is nvarchar (128).

Join our BMC Marimba training today and enhance your skills to new heights!

HKR Trainings Logo

Subscribe to our YouTube channel to get new updates..!

RETURN VALUE:

Return Value Returns the stored procedure Name if any Error has occurred in the stored procedure or trigger once the CATCH statement is blocked.

It returns the NULL value if the Error does not occur within a stored procedure or any type of trigger that is called outside the CATCH block.

The code is as follows;

CREATE procedure My_prnc
AS
BEGIN TRY
SELECT SALARY + First_Name FROM Employee Where Emp_ID = 6
END TRY
BEGIN CATCH
SELECT ERROR_PROCEDURE () As Prnc;
END CATCH;
END

OUTPUT:
01. Exec My_Prnc,

Prnc:
My_Prnc

Example 7: ERROR_SEVERITY

ERROR_SEVERITY returns the severity of the Error. The data type of ERROR_SEVERITY is Int.

The code is as follows;

BEGIN TRY

SELECT SALARY + First_Name from Employee WHERE EMP_ID = 6

END TRY

BEGIN CATCH

SELECT ERROR_SEVERITY () AS ErrorSeverity;

END CATCH;

OUTPUT:

ErrorSeverity

16

The severity level of the error message provides an indication of error type that occurred in Microsoft SQL Server. In the below example the Severity level is 15 so the system will give you a message like Permission denied.

Some Important Severity levels are;
Serial.no of severity
Description

13
Which indicates the transaction deadlock errors

14
Indicates the security-related error levels, by that time system will generate an error message like permission denied

15
This severity indicates the syntax error in the form of Transact-SQL command

16
This severity level indicates the general errors that will be corrected by the user

TRANSACTION management in Exception handling

This is a very important type of exception handling; let’s get into the full details

BEGIN TRANSACTION Trans
BEGIN TRY
DELETE From Employee Where Employee. Emp_ID <4
UPDATE EMPLOYEE SET Employee. First_Name = ‘Kavya’ where Employee. EMP_ID = ‘5
IF @@TRANSCount > 0
BEGIN COMMIT Transaction Transt
END
END TRY
BEGIN CATCH
If @@TransCount > 0
Print ‘ERROR is occurred in Transaction’
BEGIN Rollback Transaction Transt
END
END CATCH
SELECT *FROM Employee

OUTPUT:
Serial number
Emp_id
First_name
Last_name
Salary
City

1
1
Kavya
Gowda
50000
Alwar

2
2
Rahul
Chowdary
25000
Alwar

3
3
Sandeep
Prajapat
23000
Alwar

4
4
Sanjeev
Jangid
27000
Alwar

5
5
Neeraj
Baldia
24000
Alwar

6
6
Narendra
Saini
22000
Alwar

Top 30 frequently asked Maximo Interview Questions!

SQL Server Certification Training

Weekday / Weekend Batches

INSIGHT:

In this article, I have explained the important concepts about Exception handling in SQL server. The Exception is nothing but Errors that occur during the time of programming execution.The mechanism which is used to handle the Errors is called Handling. And also I have explained the properties and types of the Exception handling mechanism in the SQL server.I hope this article may help a few of you to learn the important concepts of Error handling and also enables you to communicate with experts across the world via social forums.

Related Articles:

1. Isolation Levels in SQL Server

2. SQL Server Joins

3. SQL Server Data Tools



Source link

Leave a Reply

Subscribe to Our Newsletter

Get our latest articles delivered straight to your inbox. No spam, we promise.

Recent Reviews


Google Cloud Free Tier – Table of Content

However, even when the free money has run out, the free gifts will continue. There are 24 distinct products that provide “always free” samples on a regular basis. Even if you’ve been a customer for a long time, you can still try new things. Of course, Google clarifies that the term “always” in this generous commitment is “subject to change”. Until then, the BigQuery database will process one terabyte of queries every month, and AutoML Translation will convert 500,000 characters from one language to another.

Some developers use the free tier for what it was designed for: an opportunity to explore without having to beg their bosses and bosses’ bosses for the budget. Others work on a side business or a website for the youngsters in their neighborhood. When the load is small, it’s simple to innovate without having to worry about a monthly bill.

This is taken to an extreme by some developers. They attempt to spend as little time as possible in the free tier. Maybe they want to brag about how low their burn rate is. Maybe it’s just a new kind of machismo. Perhaps they’re short on cash.

Working this free angle for as long as feasible often results in lean and efficient web applications that perform as much as possible with as little as possible. When they leave the free tier, the monthly bills will remain low as the project grows, which will make every CFO happy.

Here are some tips for getting the most out of Google’s free service. You might be a scrooge. Maybe you’re just waiting till the brilliance is fully understood before telling your boss. Maybe you’re just having fun, and this is a mistake. In any case, there are numerous ways to save.

1.Only keep what is really necessary

Free databases such as Firestore and Cloud Storage are extremely versatile solutions for storing key-value documents and objects. The always-free tier of Google Cloud allows you to store your initial 1GB and 10GB of data in each product. However, the more information your program stores, the faster the free gigabytes run out. So, unless you definitely need it, stop keeping information. This means you won’t be collecting data obsessively just in case you need it for later debugging. There are no unnecessary timestamps, and you don’t need to retain a large cache of data just in case.

Want to get certified in GCP. Learn from our experts and do excel in your career with HKR’S Google Cloud Training

2.Your ally will be compression

There are hundreds of useful pieces of code for compressing your clients’ data. Instead of storing large blocks of JSON, the client code can compress the data using LZW or Gzip before delivering it over the wire to your server instances, which will store it without unpacking it. This translates to speedier replies, fewer bandwidth concerns, and a smaller effect on your monthly data storage capacity. Be cautious, because compression overhead can cause some extremely little data packets to grow in size.

Google Cloud Training

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

3.Go without a server

Google’s intermittent compute services, which are priced per request, are more generous. Cloud Run will automatically start and run a stateless container that will answer two million requests per month for free. In response to another two million requests, Cloud Functions will launch your function. On a daily basis, that’s more than 100,000 different operations. So stop waiting and start developing serverless programs.

Note: Some architects would cringe at the thought of combining two distinct services. It may save money, but it will increase the application’s complexity, making it more difficult to maintain. That is a genuine risk, but you can often more or less recreate Cloud Functions’ function-as-a-service structure inside your own container, allowing you to condense your code later if you plan ahead.

4.Make use of the App Engine

Google App Engine is still one of the finest methods to get a web application up and running without having to worry about all of the nuances of deployment and scaling. Almost everything is automatic, so if the load increases, more instances will be deployed. The App Engine comes with 28 “instance hours” every day, which means your basic app would run for free for 24 hours a day and can even grow for four hours if demand rises.

5.Service calls should be consolidated

If you’re careful, there’s some room for extras. The amount of individual requests, not the complexity, is what sets the limit for serverless invocations. Bundling all data activities into one larger packet allows you to pack more activity and outcomes into each exchange. So you may include ridiculous gimmicks like stock quotes if you slide a few more bytes into the absolutely necessary packets. Keep in mind that Google keeps track of the amount of memory consumed and the amount of time it takes to compute. Your functions can’t use more than 400,000 GBs of memory and 200,000 GHz of computation time.

6.Make use of local storage

The current web API provides a number of useful storage options. Then there’s the perfectly delicious, old-fashioned cookie with a four-kilobyte limit. The Web Storage API is a document-based key-value system that keeps at least five megabytes of data in the cache, with certain browsers keeping up to ten megabytes. The IndexedDB provides a more comprehensive collection of capabilities, such as database cursors and indexes, to help speed up the process of sifting through large amounts of data.

The more data you save locally on your users’ machines, the less server-side storage you’ll need. This can result in speedier answers and a reduction in the amount of bandwidth used to send countless copies of data back to your server. However, there will be issues when users transfer devices because the data would most likely be out of sync. Just make sure all of the crucial facts are the same.

Want to get certified in GCP. Learn from our experts and do excel in your career with HKR’S Google Cloud Training in Hyderabad!

, Cloud Computings, google-cloud-free-tier-description-0, , Cloud Computings, google-cloud-free-tier-description-1

Subscribe to our YouTube channel to get new updates..!

7.Look for hidden bargains

Google has a page that summarizes all of the “always free” items, but if you look around, you’ll find plenty of other free services that aren’t on the list. For example, Google Maps gives “$200 in free monthly usage.” Google Docs and a few more APIs are always available for free.

8.Make use of G Suite

Many G Suite products, such as Docs, Sheets, and Drive, are invoiced separately, and customers can access them for free with their Gmail account or pay for them as a package. Rather than developing an app with built-in reporting, simply export the data to a spreadsheet and share it. The spreadsheets are capable of displaying graphs and plots in the same way that a dashboard would. To handle interactive requests, you’ll need to burn through your compute and data quotas if you construct a web app. However, if you simply create a Google Doc for your report, you’ll be throwing the majority of the work onto Google’s servers.

Click here to get frequently asked Google Cloud interview questions & answers

Check out our Latest Interview Questions video. Register Now  Google Cloud Online Training to Become an expert in Google Cloud.

9.Get rid of the gimmicks

Modern online applications have some functionalities that are largely unnecessary. Is it necessary to include stock quotes in your bank application? Is it necessary to provide the time or temperature in the local time zone? Do you need to include the most recent tweets or Instagram photographs in your post? No. Remove all of these extras because each one necessitates a new request to your server computers, reducing your available bandwidth. The product design team may have big aspirations, but you have the power to say “No!” to them.

10.Be cautious with new options

Some of the most advanced technologies for developing artificial intelligence services for your stack provide you plenty of room to experiment. Before costs kick in, the AutoML Video service allows you to train your machine learning model on video streams for 40 hours each month. For six hours, the service for tabular data will mill your rows and rows of data on a node free of charge. This provides you enough rope to play around with or make simple models, but be careful. It would be risky to automate the procedure so that each user may initiate a large machine learning task.

Acquire GCP certification by enrolling in the HKR GCP Training in Banglore!

Google Cloud Training

Weekday / Weekend Batches

11.Keep your expenses in perspective

It’s all too easy to take this game too far and convert your app’s architecture into a Rube Goldberg device only to save a few dollars. It’s crucial to note that in Google Cloud, the transition from free to paid is frequently a very small one. While many free services on the Internet can easily go from free to thousands of dollars with a single click, Google’s offerings aren’t usually priced that way.

Following two million free Cloud Function invocations, the next one costs $0.0000004. That works out to just 40 cents per million. You should be able to cover a few extra million with ease if you search through your sock drawer.

When you leave the free zone, the price schedule is generous enough that you won’t suffer a heart attack. If your application requires a few million dollars more here or there, you’ll most likely be able to cover it. The main takeaway is that reducing the computing burden results in smaller bills and faster responses.

Conclusion:

We hope this blog has provided the necessary information and you have learned various tips which assisted you in making the best use of free tier services in google cloud. 

Related blog:

AWS vs Azure vs Google Cloud

HPE Simplivity Training



Source link