cs notebook0
  • Introduction
  • Core Java
  • some notes
  • Data structure&algorithm
  • Garbage Collection
  • HashMap
  • Collection0
  • Collection1
  • Collection2
  • comparatorVScomparable
  • exception0
  • exception1
  • exception2
  • Enum in Java
  • JVM
  • Wrapper Classes in Java
  • String, int convert
  • HashSetVSTreeSetVSLinkedHashSet
  • Pair
Powered by GitBook
On this page
  • 0. java.lang.Throwable
  • 1. Exception Handling in Java
  • 1.1 What is exception?
  • 1.2 What is exception handling?
  • 1.3 Advantage of Exception Handling
  • 1.4 Hierarchy of Java Exception classes
  • 1.5 Types of Exception
  • 1.6 Difference between checked and unchecked exceptions
  • 1.7 Java Exception Handling Keywords
  • 2. Java try-catch
  • 2.1 Java try block
  • 2.2 Java catch block
  • 2.3 Internal working of java try-catch block
  • 3. Java catch multiple exceptions
  • 3.1 Catching Multiple Exceptions in Java7
  • 4. Java Nested try block
  • 4.1 Why use nested try block
  • 4.2 Syntax
  • 5. Java finally block
  • Why use java finally?
  • 6. Java throw exception
  • 6.1 Java throw keyword

Was this helpful?

exception0

PreviouscomparatorVScomparableNextexception1

Last updated 5 years ago

Was this helpful?

0. java.lang.Throwable

java.lang.Throwable class is the superclass of all errors and exceptions in the java language.

1. Exception Handling in Java

java.lang.Exceptions provides for different exceptions thrown under java lang package.

1.1 What is exception?

In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.

1.2 What is exception handling?

It is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc.

1.3 Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application.

The code will continue execute after the exception has been handled.

1.4 Hierarchy of Java Exception classes

1.5 Types of Exception

  • Checked Exception

  • Unchecked Exception

  • Error

1.6 Difference between checked and unchecked exceptions

1) Checked Exception

The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.

2)Unchecked Exception

The classes that extend RuntimeException are know as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.

e.g.

  1. https://en.wikibooks.org/wiki/Java\_Programming/Preventing\_NullPointerException
    
    These include:
  2. Calling an instance method on the object referred by a null reference.

  3. Accessing or modifying an instance field of the object referred by a null reference.

  4. If the reference type is an array type, taking the length of a null reference.

  5. If the reference type is an array type, accessing or modifying the slots of a null reference.

  6. If the reference type is a subtype ofThrowable, throwing a null reference.

  7. NumberFormatException: A JavaNumberFormatExceptionusually occurs when you try to do something like convert a Stringto a numeric value, like an int, float, double, long, etc.

3)Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

1.7 Java Exception Handling Keywords

  • try

  • catch

  • finally

  • throw

  • throws

2. Java try-catch

2.1 Java try block

Java try block is used to enclose the code that might throw an exception. It must be used within the method.

Java try block must be followed by either catch or finally block.

2.2 Java catch block

Java catch block is used to handle the exception. It must be used after the try block only.

You can use multiple catch block with a single try.

2.3 Internal working of java try-catch block

3. Java catch multiple exceptions

If you have to perform different tasks at the occurrence of different Exceptions, use java multi catch bock.

e.g.

try{
    int a[]=new int[5];
    a[5]=30/0;
}
catch(ArithmeticException e){System.out.println("task 1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
catch(Exception e){System.out.println("common task completed");}

RULES:

  • At a time only one Exception is occured and at a time only one catch block is executed.

  • All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception.----Hierarchies

3.1 Catching Multiple Exceptions in Java7

In Java 7, we can catch multiple exceptions using the multi catch syntax:

try {

    // execute code that may throw 1 of the 3 exceptions below.

} catch(SQLException | IOException e) {
    logger.log(e);

} catch(Exception e) {
    logger.severe(e);
}

4. Java Nested try block

The try block within a try block is known as nested try block in java.

4.1 Why use 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.

4.2 Syntax

...
try{
    statement 1;
    stateemnt 2;
    try{
        statement 3;
        statement 4;
    }catch(Exception e){
        ...
    }
}catch(Exception e){
    ...
}
...

5. Java finally block

Java finally block is a block that is used to execute important code such closing connection, steam etc.

Java finally block is always executed whether exception is handled or not.

Java finally block follows try or catch block.

Why use java finally?

finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc.

6. Java throw exception

6.1 Java throw keyword

The java throw keyword is used to explicitly throw an exception.

We can throw either checked or unchecked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception.

Syntax:

throw exception;

e.g.1

throw new IOException("Sorry device error");

e.g.2

public class exe1{

    static void validata(int age){
        if(age>18)
            throw new ArithmeticException("not valid");
        else System.out.println("welcome");
    }
public static void main(String[] args) {
    validata(87);
    System.out.println("rest of code");
}

}

If a method declares that is throws an exception A, then it is also legal to throw subclasses of A.

NullPointerException: In Java, a specialvalue can be assigned to an object reference.NullPointerExceptionis thrown when an application attempts to use an object reference that has thevalue.

https://www.javatpoint.com/try-catch-block
null
null