0% found this document useful (0 votes)
29 views

Unit 4-Exception

Java

Uploaded by

Aryan Gireesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Unit 4-Exception

Java

Uploaded by

Aryan Gireesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Exception Handling

Exception:
Exception is an abnormal condition or Exception is run time error.

Exception is a error that arises during the execution of a program

When an Exception occurs the normal flow of the program is


disrupted, and the program/Application terminates abnormally, we
want to continue execution of program then display an appropriate
message for taking corrective action. This is called Exception
Handling.
Java provides two types Exceptions:

1)Checked Exception

2)Unchecked Exception
Checked exceptions − A checked exception is an exception that
occurs at the compile time, these are also called as compile time
exceptions. These exceptions cannot simply be ignored at the
time of compilation, the programmer should take care of
(handle) these exceptions.

List of Checked Exception:


1.NoSuchFieldException
2.IllegalAccessException
3.ClassNotFoundException
4NoSuchMethodException
5.InterruptedException
6.FileNotFoundException
Unchecked exceptions − An unchecked exception is an exception
that occurs at the time of execution. These are also called as
Runtime Exceptions. These include programming bugs, such as
logic errors or improper use of an API. Runtime exceptions are
ignored at the time of compilation.

For example, if you have declared an array of size 5 in your


program, and trying to call the 6th element of the array then an
ArrayIndexOutOfBoundsException occurs.
Exception handling is associated with following keyword:
1)try
2)Catch
3)Finally
4)throw
5)throws
Common Unchecked Exception

1.ArithmeticException

2.ArrayindexOutOfBoundsException

3.FileNotFoundException

4)NullPointerException

5.NumberFormatException

6.NegativeArraySizeException
class demo
{
public static void main(String args[])
{
int a,b,c;
try
{
a=18
b = 0;
c = a / b;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{
// catch divide-by-zero error
System.out.println("Division by zero.");
}
finally
{
System.out.println(“This final statement.");
}
}
Nested Try Catch:
If one try catch is inside other try catch block then it is called as
Nested try catch
class NestTry
{
public static void main(String args[])
{
try
{
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
try
{
if(a==1) a = a/(a-a); // division by zero
if(a==2)
{
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out-of-bounds: " + e);
}
}
catch(ArithmeticException e)
{ System.out.println(e); }
} }
Multiple catch
In some cases, more than one exception could be raised by a single piece of code.
To handle this type of situation, you can specify two or more catch clauses, each
catching a different type of exception.
class MultiCatch
{
public static void main(String args[])
{
try
{
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}}
throw keyword
The Java throw keyword is used to explicitly throw an
exception.
We can throw either checked or uncheked exception in java by
throw keyword.

The syntax of java throw keyword is given below.

throw exception;

Eg:
throw new IOException("sorry device error);
//Example for throw keyword...

public class throwdemo


{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{
validate(13);
System.out.println("rest of the code...");
}
}
throws keyword
The Java throws keyword is used to declare an exception.
It gives an information to the programmer that there may occur an
exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained.
Whenever a program does not want to handle exceptions using
try catch block,it can use throws clause.

Syntax of java throws


return_type method_name() throws exception_class_name
{
//method code
}
User defined Exception
you are creating your own Exception that is known as custom
exception or user-defined exception. By the help of custom
exception, you can have your own exception and message.

Example

class InvalidAgeException extends Exception


{
InvalidAgeException(String s)
{
super(s);
}
}
Difference between throw & throws
No. throw throws
Java throw keyword is used to Java throws keyword is used to
1)
explicitly throw an exception. declare an exception.

Checked exception cannot be Checked exception can be


2)
propagated using throw only. propagated with throws.

3) Throw is followed by an instance. Throws is followed by class.

Throws is used with the method


4) Throw is used within the method.
signature.

You can declare multiple exceptions


You cannot throw multiple e.g.
5)
exceptions. public void method()throws
IOException,SQLException.
Throwable Class:
The Throwable class is the superclass of every error and exception in the
Java language. Only objects that are one of the subclasses this class are
thrown by any “Java Virtual Machine” or may be thrown by the Java
throw statement.

Class Declaration
Following is the declaration for java.lang.Throwable class −

public class Throwable extends Object implements Serializable


Public Constructors
Throwable(): It is a non-parameterized constructor which constructs a
new Throwable with null as its detailed message.

Throwable(String message): It is a parameterized constructor which


constructs a new Throwable with the specific detailed message.

Throwable(String message, Throwable cause): It is a parameterized


constructor which constructs a new Throwable with the specific detailed
message and a cause.

Throwable(Throwable cause): It is a parameterized constructor which


constructs a new Throwable with the specific cause and a detailed
message of the cause by converting the case to the String using toString()
method.
Methods:

1.Throwable fillInStackTrace():This method fills in the execution stack trace.

2. Throwable getCause():This method returns the cause of this throwable or null


if the cause is nonexistent or unknown.

3 String getLocalizedMessage():This method creates a localized description of


this throwable.

4 String getMessage():This method returns the detail message string of this


throwable.

5 StackTraceElement[] getStackTrace():
This method provides programmatic access to the stack trace information printed
by printStackTrace().

6 Throwable initCause(Throwable cause): This method initializes the cause of


this throwable to the specified value.
7.void printStackTrace(): This method prints this throwable and its backtrace
to the standard error stream.

8. void printStackTrace(PrintStream s):This method prints this throwable


and its backtrace to the specified print stream.

9 void printStackTrace(PrintWriter s):This method prints this throwable and


its backtrace to the specified print writer.

10 void setStackTrace(StackTraceElement[] stackTrace):This method sets


the stack trace elements that will be returned by getStackTrace() and printed by
printStackTrace() and related methods.

11 String toString(): This method returns a short description of this throwable.

You might also like