What is an exception?
An Exception is an unwanted event that interrupts the normal flow of the program. When an exception occurs program execution gets terminated. In such cases we get a system generated error message. By handling the exceptions we can provide a meaningful message to the user about the issue rather than a system generated message.
What is Exception Handling?
Exception handling is one of the most important feature of java programming that allows us to handle the runtime errors caused by exceptions. If an exception occurs, which has not been handled by programmer then program execution gets terminated and a system generated error message is shown to the user. This message is not user friendly so a user will not be able to understand what went wrong. In order to let them know the reason in simple language, we handle exceptions. We handle such conditions and then prints a user friendly warning message to user, which lets them correct the error as most of the time exception occurs due to bad data provided by user.
What are Errors?
Errors indicate that something severe enough has gone wrong, the application should crash rather than try to handle the error. Error is usually an irreversible and irrecoverable situation in a program and when an error occurs, the programs crash. Some of the examples of errors in a program are OutOfMemoryError, AssertionError, and VirtualMachineError, etc.
public class Error
{
public static void main(String[] args)
{
System.out.println("1");
System.out.println("2");
System.out.println("3");
System.out.println("4");
System.out.println(45/0);
System.out.println("5");
System.out.println("6");
System.out.println("7");
System.out.println("8");
}
}
Output:
C:\Users\student\Desktop>javac Error.java
C:\Users\student\Desktop>java Error
1
2
3
4
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Error.main(Error.java:9)
What are Exceptions?
Exceptions are events that occurs in the code. A programmer can handle such conditions and take necessary corrective actions.
Examples : Names of few pre-defined Exceptions.
NullPointerException – When you try to use a reference that points to null.
NullPointerException – When you try to use a reference that points to null.
ArithmeticException – When bad data is provided by user, for example, when you try to divide a number by zero this exception occurs because dividing a number by zero is undefined.
ArrayIndexOutOfBoundsException – When you try to access the elements of an array out of its bounds, for example array size is 5 (which means it has five elements) and you are trying to access the 10th element.
There are two types of exceptions in Java:
1)Checked exceptions
2)Unchecked exceptions
1.Checked exceptions
2.Unchecked Exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks them during compilation.
Ex: SQLException, IOException, ClassNotFoundException etc.
2.Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked at compile-time.
Ex: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.Write about Try block.
Syntax:
The try block contains set of statements where an exception can occur. A try block is always followed by a catch block, which handles the exception that occurs in associated try block. A try block must be followed by catch block(s) or finally block or both.
try
{
//statements that may cause an exception
}
{
//statements that may cause an exception
}
Write about Catch block.
Syntax:
try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}
A catch block is where you handle the exceptions. This block must follow the try block. A single try block can have several catch blocks associated with it. For example if an arithmetic exception occurs in try block then the statements enclosed in catch block for arithmetic exception executes.
try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}
Write about Throw block.
We can define our own set of conditions or rules and throw an exception explicitly using throw keyword. For example, we can throw ArithmeticException when we divide number by 5, or any other numbers.
Syntax:
throw new exception_class("error message"); Ex:
throw new ArithmeticException("dividing a number by 5 is not allowed in this program");
throw new ArithmeticException("dividing a number by 5 is not allowed in this program");
Write about Finally block.
A finally block contains all the crucial statements that must be executed whether exception occurs or not. The statements present in this block will always execute regardless of whether exception occurs in try block or not such as closing a connection, stream etc.
try
{
//Statements that may cause an exception
}
catch
{
//Handling exception
}
finally
{
//Statements to be executed
}
Example on try with single catch
class Rksc
{
public static void main(String args[])
{
int n1,n2;
try
{
n1 = 0;
n2 = 62/n1;
System.out.println(n2);
System.out.println("This is Last Statement in try block");
}
catch (ArithmeticException e)
{
System.out.println("Division with zero is not allowed");
}
System.out.println("This line is Outside of Try-Catch block");
}
}
Output:
C:\Users\student\Desktop>javac Rksc.java
C:\Users\student\Desktop>java Rksc
Division with zero is not allowed
This line is Outside of Try-Catch block
Example on try with multiple catch
Output:
class Rk
{
public static void main(String args[])
{
int n1,n2;
try
{
n1 = 0;
n2 = 62/n1;
System.out.println(n2);
System.out.println("This is Last Statement in try block");
}
catch (ArithmeticException e)
{
System.out.println("Division with zero is not allowed");
}
catch (Exception e)
{
System.out.println("An Exception Happened");
}
System.out.println("This line is Outside of Try-Catch block");
}
}
C:\Users\Student\Desktop\java prg>javac Rk.java
C:\Users\Student\Desktop\java prg>java Rk
Division with zero is not allowed
This line is Outside of Try-Catch block
Example on try with multiple catch
class Rkmc
{
public static void main(String args[])
{
try
{
int a[]=new int[7];
a[4]=30/0;
System.out.println("This statement is in try block");
}
catch(ArithmeticException e)
{
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e)
{
System.out.println("Warning: Some Other exception");
}
System.out.println("Control is Out of try-catch block");
}
}
Output:
C:\Users\student\Desktop>javac Rkmc.java
C:\Users\student\Desktop>java Rkmc
Warning: ArithmeticException
Control is Out of try-catch block
Ex3: Using throw keyword
class Rkthrow
{
static void checkEligibilty(int stuage, int stuweight)
{
if(stuage<12 && stuweight<40)
{
throw new ArithmeticException("Student Age or Weight not Matched Cannot Regiser");
}
else
{
System.out.println("Student Entry is Valid!!");
}
}
public static void main(String args[])
{
System.out.println("Welcome to the Registration process!!");
checkEligibilty(10, 39);
System.out.println("Have a Good Day");
}
}
Output:
C:\Users\Student\Desktop\java prg>javac Rkthrow.java
C:\Users\Student\Desktop\java prg>java Rkthrow
Welcome to the Registration process!!
Exception in thread "main" java.lang.ArithmeticException: Student Age or Weight not Matched Cannot Regiser
at Rkthrow.checkEligibilty(rkthrow.java:7)
at Rkthrow.main(rkthrow.java:16)
Ex4: try...catch...finally... throws
class RkExcep
{
static void rkMethod(int testnum)throws Exception
{
System.out.println ("Start - MyMethod");
if (testnum == 12)
throw new Exception();
System.out.println("End - MyMethod");
return;
}
public static void main(String args[])
{
int testnum = 12;
try
{
System.out.println("Try - First Statement");
rkMethod(testnum);
System.out.println("Try - Last Statement");
}
catch ( Exception ex)
{
System.out.println("An Exception");
}
finally
{
System.out.println( "Finally") ;
}
System.out.println("Out of Try / Catch / Finally - statement");
}
}
Output:
C:\Users\Student\Desktop\java prg>javac RkExcep.java
C:\Users\Student\Desktop\java prg>java RkExcep
Try - First Statement
Start - MyMethod
An Exception
Finally
Out of Try / Catch / Finally - statement
No comments:
Post a Comment