Showing posts with label Exception. Show all posts
Showing posts with label Exception. Show all posts

Tuesday 28 February 2023

What is a DivideByZeroException?

An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.

A "DivideByZeroException" is a type of exception that can be thrown in programming languages like C# and Java when an attempt is made to divide a number by zero. This exception is typically thrown at runtime when the code attempts to execute a division operation and encounters a zero value in the denominator.

When a "DivideByZeroException" is thrown, it can cause the program to crash or behave unpredictably. To handle this exception, you can use a try-catch block in your code that catches the exception and handles it appropriately. For example, you might display an error message to the user or log the error to a file.

To avoid the "DivideByZeroException" altogether, it's important to check that the denominator is not zero before attempting a division operation. This can be done using conditional statements in your code that check the value of the denominator before executing the division operation.

Example

int numerator = 10;
int denominator = 0;

try
{
    int result = numerator / denominator;
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Cannot divide by zero");
    Console.WriteLine(ex.Message);
}


In this example, the numerator is 10 and the denominator is 0, which will result in a divide by zero error when trying to calculate the result value. To handle this error, we put the code in a try-catch block, where the catch block will catch the DivideByZeroException and print an error message.

Note that you should always avoid dividing by zero in your code. If there is a possibility that the denominator can be zero, you should check for this condition before attempting the division.

Wednesday 3 August 2022

What is an Exception?

An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.

Many different kinds of errors can cause exceptions: problems ranging from serious hardware errors, such as a hard disk crash, to simple programming errors, such as trying to access an out-of-bounds array element. When such an error occurs within a Java method, the method creates an exception object and hands it off to the runtime system. The exception object contains information about the exception including its type and the state of the program when the error occurred. The runtime system is then responsible for finding some code to handle the error. In terminology, creating an exception object and handing it to the runtime system is called throwing an exception.

Types of exceptions :

1. Checked exceptions
2. Unchecked exceptions

Examples of exceptions : 

The following are examples of exceptions:

1. ClassNotFoundException
2. IllegalStateException
3. IllegalArgumentException
4. NullPointerException
5. SQLException

What is a NullReferenceException?

An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.

Many different kinds of exceptions occur NullReferenceException is one of the exceptions which occurs.

NullReferenceException occurs when you try to use something that is null. This means the value is either set to null, or the value is never set to it.

Like anything else, null gets passed around. If it is null in method "A", it could be that method "B" passed a null to method "A".

null can have different meanings:

1. Object variables that are uninitialized and hence point to nothing. In this case, if you access members of such objects, it causes a NullReferenceException.

2. The developer is using null intentionally to indicate there is no meaningful value available. 

To prevent the NullReferenceException exception, check whether the reference type parameters are null or not before accessing them. If an object can return null, simply check that object's value before trying to access the properties/methods. I would never allow an exception to be thrown and interrupt the standard program flow just to catch an Exception and log it.

Example of null reference

Check whether an object contains a null value or not using an if condition, as shown below:

public class Program
{
public static void Main()
{
IList<string> companies = null;
DisplayCompany(companies);
}

public static void DisplayCompany(IList<string> companies)
{
if (companies == null) //check null before accessing
{
Console.WriteLine("No companies");
return;
}

foreach (var company in companies)
{
Console.WriteLine(company);
}
}
}

In the above example, if(companies == null) checks whether the companies object is null or not. If it is null then display the appropriate message and return from the function.

Types of Exceptions

Exception handling is the process of responding to unwanted or unexpected events when a computer program runs. Exception handling deals with these events to avoid the program or system crashing, and without this process, exceptions would disrupt the normal operation of a program.

Types of exceptions :

Exceptions can come in the following two exception classes:

1. Checked exceptions

Also called compile-time exceptions, the compiler checks these exceptions during the compilation process to confirm if the exception is being handled by the programmer. If not, then a compilation error displays on the system. Checked exceptions include SQLException and ClassNotFoundException.

2. Unchecked exceptions

Also called runtime exceptions, these exceptions occur during program execution. These exceptions are not checked at compile time, so the programmer is responsible for handling these exceptions. Unchecked exceptions do not give compilation errors. Examples of unchecked exceptions include NullPointerException and IllegalArgumentException.

Examples of exceptions

The following are examples of exceptions:

SQLException: is a checked exception that occurs while executing queries on a database for Structured Query Language syntax.

ClassNotFoundException: is a checked exception that occurs when the required class is not found -- either due to a command-line error, a missing CLASS file, or an issue with the classpath.

IllegalStateException: is an unchecked exception that occurs when an environment's state does not match the operation being executed.

IllegalArgumentException: is an unchecked exception that occurs when an incorrect argument is passed to a method.

NullPointerException: is an unchecked exception that occurs when a user tries to access an object using a reference variable that is null or empty.


What is exception handling?

Exception handling is the process of responding to unwanted or unexpected events when a computer program runs. Exception handling deals with these events to avoid the program or system crashing, and without this process, exceptions would disrupt the normal operation of a program.

Exceptions occur for numerous reasons, including invalid user input, code errors, device failure, the loss of a network connection, insufficient memory to run an application, a memory conflict with another program, a program attempting to divide by zero, or a user attempting to open files that are unavailable.

When an exception occurs, specialized programming language constructs, interrupt hardware mechanisms, or operating system interprocess communication facilities handle the exception.
Exception handling differs from error handling in that the former involves conditions an application might catch versus serious problems an application might want to avoid. In contrast, error handling helps maintain the normal flow of software program execution.

How is exception handling used?

If a program has a lot of statements and an exception happens halfway through its execution, the statements after the exception do not execute, and the program crashes. Exception handling helps ensure this does not happen when an exception occurs.

Exception handling can catch and throw exceptions. If a detecting function in a block of code cannot deal with an anomaly, the exception is thrown to a function that can handle the exception. A catch statement is a group of statements that handle the specific thrown exception. Catch parameters determine the specific type of exception that is thrown.

Exception handling is useful for dealing with exceptions that cannot be handled locally. Instead of showing an error status in the program, the exception handler transfers control to where the error can be handled. A function can throw exceptions or can choose to handle exceptions.

Error handling code can also be separated from normal code with the use of try blocks, which is code that is enclosed in curly braces or brackets that could cause an exception. Try blocks can help programmers to categorize exception objects.