Lecture-28 Java SE (Exception Handling-2)
Lecture-28 Java SE (Exception Handling-2)
Lecture-28
Today’s Agenda
01 Obtaining description of an Exception
05
Obtaining description Exception
•Now using that object we can obtain all the possible details of the exception that
occurred in the catch block.
•To do this we can use several methods using the object reference. Some important and
common methods are :
Methods
• public String getMessage( ):-
This method is present in the class Throwable.
The method returns “error message” generated by java regarding the exception.
Example:- catch(Exception e)
{
System.out.println(e.getMessage());
}
• So, by overriding the toString() method we can get information related to a specific
class and not hashcode.
Objects and Classes
class Person class UsePerson
{ {
public static void main(String [ ]
private int age; args)
{
private String name; Person p=new Person(21,“Amit”);
System.out.println(p);
public Person(int age, String }
name) }
{
this.age=age;
this.name=name;
}
•The exception classes have also overridden toString() method, it returns the name
of exception along with error message for an exception generated by java.
•The toString() of specific exception class is called as per the object formed in the
try block.
Using “throw” keyword
•In java, exceptions occur on JVM’s choice i.e. anything against java’s flow. Example, if
denominator is 0 then java itself generates ArithmeticException.
Checked Unchecked
Exceptions Exceptions
Exceptions for which java forces the Exceptions for which java never compels the
programmer to either handle it using programmer to handle it.The program would
try-catch or the programmer must inform be compiled and executed by Java.Example
or warn the caller of the method that his the class RuntimeException and all its
code is not handling the checked exception. derived classes fall in this category.
• The caller also has 2 options, either use try-catch or the keyword throws.
• If every method uses throws, then ultimately the responsibility goes to the JVM
which will follow the standard mechanism of handling the exception.
• All exceptions which are not derived classes of RuntimeException fall in this
category. Like SQLException, IOException, InterruptedException etc…
Code for Checked Exception
import java.io.*;
class Input
{
public static void accept( ) throws IOException
{
System.out.println(“Enter a character”);
char c=(char)System.in.read( );
System.out.println(“You entered ”+c);
}
}
class UseInput
{
public static void main(String [] args) throws IOException
{
Input.accept( );
}
}
Thank you