0% found this document useful (0 votes)
19 views26 pages

Exceptions New Copy

Uploaded by

C.M Srinivas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views26 pages

Exceptions New Copy

Uploaded by

C.M Srinivas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Exceptions

• An exception is an unexpected event, which may occur during the


execution of a program (at run time), to disrupt the normal flow of
the program’s instructions. This leads to the abnormal termination of
the program, which is not always recommended.
• An exception may occur due to the following reasons. They are.
• Invalid data as input.
• Network connection may be disturbed in the middle of
communications
• JVM may run out of memory.
• File cannot be found/opened. These exceptions are caused by
user error, programmer error, and physical resources.
• powerful mechanisms to handle the runtime errors so that normal flow of the application
can be maintained.
• Based on these, the exceptions can be classified into three categories.
• Checked exceptions
• Unchecked exceptions
• Errors
• A checked exception is an exception that occurs at the compile time, also called as compile
time (static time) exceptions. These exceptions cannot be ignored at the time of compilation.
So, the programmer should handle these exceptions.
• An unchecked exception is an exception that occurs at run time, 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.
• Errors are not exceptions, but problems may arise beyond the control of the user or the
programmer. Errors are typically ignored in your code because you can rarely do anything
about an error.
• For example, if a stack overflow occurs, an error will arise. They are also ignored at the time
of compilation.
• Error: An Error indicates serious problem that a reasonable
application should not try to catch.
• Exception: catch. Exception indicates conditions that a reasonable
application might try to catch.
• Exception Hierarchy:
• The java.lang.Exception class is the base class for all exception classes.
All exception and errors types are sub classes of class Throwable,
which is base class of hierarchy.
• This class is used for exceptional conditions that user programs should
catch. NullPointerException is an example of such an exception.
• Error are used by the Java run-time system(JVM) to indicate errors
having to do with the run- time environment itself(JRE).
StackOverflowError is an example of such an error.
• Errors are abnormal conditions that happen in case of severe failures,
these are not handled by the Java programs.
• Errors are generated to indicate errors generated by the runtime
environment.
• Example: JVM is out of memory. Normally, programs cannot recover
from errors.
• The Exception class has two main subclasses: IOException class and
RuntimeException Class.
Exceptions Methods
Method Description
Returns a detailed message about the exception that has occurred.
public String getMessage() This message is initialized in the Throwable constructor.

Returns the cause of the exception as represented by a Throwable


public Throwable getCause() object.
Returns the name of the class concatenated with the re- sult of
public String toString() getMessage().
Prints the result of toString() along with the stack trace to System.err,
public void printStackTrace() the error output stream.
public StackTraceElement [] Returns an array containing each element on the stack trace. The
element at index 0 represents the top of the call stack, and the last
getStackTrace() element in the array represents the method at the bottom of the call
stack.

public Throwable Fills the stack trace of this Throwable object with the current stack
trace, adding to any previous information in the stack trace.
fillInStackTrace()
Exception handling in java uses the following Keywords

• 1.try
• 2. catch
• 3. finally
• 4.throw
• 5.throws
• The try/catch block is used as follows:
• try {
• // block of code to monitor for errors
• // the code you think can raise an exception
•}
• catch (ExceptionType1 exOb) {
• // exception handler for ExceptionType1
• } catch (ExceptionType2 exOb) {
• // exception handler for ExceptionType
• } // optional
• finally { // block of code to be executed after try block ends
• }
Uncaught Exceptions
• class Exc0 {
• public static void main(String[] args) {
• int d = 0; int a = 42 / d;
• }
•}
• java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4)
Using try and catch
• Although the default exception handler provided by the Java run time
system is useful for debugging, you will usually want to handle an
exception yourself.
• Doing so provides two benefits. First, it allows you to fix the error.
Second, it prevents the program from automatically terminating.
• class Exc2 {
• public static void main(String[] args) {
• int d, a; try {
• // monitor a block of code.
• d = 0; a = 42 / d;
• System.out.println("This will not be printed.");
• }
• catch (ArithmeticException e) { // catch divide-by-zero error
• System.out.println("Division by zero."); }
• System.out.println("After catch statement."); } }
• OUTPUT:
• This program generates the following output:
• Division by zero. After catch statement.
nested try block
• Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error.
• In such cases, exception handlers have to be nested.
• try {
• statement 1;
• statement 2;
• try {
• statement 1;
• statement 2;
• }
• catch(Exception e) { }
• }
• catch(Exception e) { }
• The following program is an example for Nested try statements.
• class Nestedtry_Example{
• public static void main(String args[]){
• try{
• System.out.println(“division”);
• int a,b; a=0; b =10/a;
• }
• catch(ArithmeticException e) { System.out.println(e); }
• try { int a[]=new int[5]; a[6]=3; }
catch(ArrayIndexOutOfBoundsException e) {
• System.out.println(e); }
• System.out.println(“other statement); }
• catch(Exception e) { System.out.println(“handeled”);}
System.out.println(“normal flow..”); }
• }
Java throw Keyword Definition and
Usage
The throw keyword is used to create a custom error.

The throw statement is used together with an exception type.

There are many exception types available in Java:


ArithmeticException,
ClassNotFoundException,
ArrayIndexOutOfBoundsException,
SecurityException, etc.
The exception type is often used together with a custom method,
• The general form of throw is shown here:

throw ThrowableInstance;
• // Demonstrate throw.
• class ThrowDemo {
• static void demoproc() {
• try {
• throw new NullPointerException("demo");
• } catch(NullPointerException e) {
• System.out.println("Caught inside demoproc.");
• throw e; // rethrow the exception
• }
• }
• public static void main(String[] args) {
• try {
• demoproc();
• } catch(NullPointerException e) {
• System.out.println("Recaught: " + e);
• }
• }
• }
Java throw Keyword
• public class Main {
• static void checkAge(int age) {
• if (age < 18) {
• throw new ArithmeticException("Access denied - You must be at least 18 years old.");
• } else {
• System.out.println("Access granted - You are old enough!");
• }
• }
• public static void main(String[] args) {
• checkAge(15);
• }
• }
• Exception in thread "main" java.lang.ArithmeticException: Access denied - You must be at least 18
years old.
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)
the throws/throw Keywords
• If a method does not handle a checked exception,
• the method must be declared using the throws keyword.
• The throws keyword appears at the end of a method’s signature.
• The difference between throws and throw keywords is that:
• throws is used to postpone the handling of a checked exception and
throw is used to invoke an exception explicitly.
• The following method declares that it throws a Remote Exception −
Example import java.io.*;
• public class throw_Example1 {
• public void function(int a) throws RemoteException {
• // Method implementation throw new RemoteException();
• } // Remainder of class definition }
• A method can declare that it throws more than one exception, in
which case the exceptions are declared in a list separated by commas.
For example, the following method declares that it throws a
RemoteException and an ArithmeticException −
• import java.io.*;
• public class throw_Example2 {
• public void function(int a) throws
RemoteException,ArithmeticException {
• // Method implementation }
• // Remainder of class definition }
• the Finally Block
• The finally block follows a try block or a catch block. A finally block of
code always executes, irrespective of the occurrence of an Exception.
A finally block appears at the end of the catch blocks that follows the
below syntax.
• Syntax try { // Protected code }
• catch (ExceptionType1 e1) { // Catch block }
• catch (ExceptionType2 e2) { // Catch block }
• finally { // The finally block always executes. }
• Example public class Finally_Example {
• public static void main(String args[]) {
• try {int a,b; a=0; b=10/a; }
• catch (ArithmeticException e) {
• System.out.println(“Exception thrown :” + e); }
• finally { System.out.println(“The finally block is executed”); }
}
• }
points to remember:
• A catch clause cannot exist without a try statement.

• It is not compulsory to have finally clauses whenever a try/catch


block is present.
• The try block cannot be present without either catch clause or
finally clause.
• Any code cannot be present in between the try, catch, finally
blocks.

You might also like