0% found this document useful (0 votes)
5 views16 pages

Java Exception Handling Basics

The document explains the concept of exception handling in Java, emphasizing the importance of declaring exceptions using a 'throws' clause in method signatures. It covers the use of 'finally' blocks to ensure certain code executes regardless of exceptions, and discusses creating user-defined exceptions by subclassing the Exception class. Additionally, it provides code examples to illustrate these concepts in practice.

Uploaded by

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

Java Exception Handling Basics

The document explains the concept of exception handling in Java, emphasizing the importance of declaring exceptions using a 'throws' clause in method signatures. It covers the use of 'finally' blocks to ensure certain code executes regardless of exceptions, and discusses creating user-defined exceptions by subclassing the Exception class. Additionally, it provides code examples to illustrate these concepts in practice.

Uploaded by

sumitjalan3534
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

throws

• If a method is capable of causing an exception that it does not


handle, it must specify this behavior so that callers of the method can
guard themselves against that exception.
• You do this by including a throws clause in the method’s
declaration.
• A throws clause lists the types of exceptions that a method might
throw.
• This is necessary for all exceptions, except those of type Error or
RuntimeException, or any of their subclasses.
• All other exceptions that a method can throw must be declared in the
throws clause.
• If they are not, a compile-time error will result.
throws
type method-name(parameter-list) throws exception-list
{
// body of method
}
• Here, exception-list is a comma-separated list of the
exceptions that a method can throw.
• If a method throws a checked exception but does not declare
it, a compile-time error occurs.
To resolve this error, either declare the exception type using
throws in the method signature or handle it with a try-catch
block.
package package_exception;
import [Link];
import [Link];
import [Link];
class FileDemo {
void readFile(String fileName) throws IOException {
File file = new File(fileName); // create File object
FileReader fr = new FileReader(file); // may throw FileNotFoundException
[Link]("File " + fileName + " opened successfully!");
[Link]();
}
}
public class FileExample {
// main also declares throws (no try-catch here)
public static void main(String[] args) {
FileDemo fe = new FileDemo();
[Link]("[Link]"); // make sure [Link] exists, or exception will be thrown
}
}
class ThrowsCheckedExample {
// This method declares that it may throw InterruptedException
static void pauseThread() throws InterruptedException {
[Link]("Thread is going to sleep for 5 seconds...");
[Link](5000); // may throw InterruptedException
[Link]("Thread woke up!");
}
public static void main(String[] args) {
try {
pauseThread(); // calling method that throws checked exception
} catch (InterruptedException e) {
[Link]("Thread was interrupted: " + [Link]());
}
}
}
// This program contains an error and will not compile.
class ThrowsDemo {
static void throwOne() {
[Link]("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
throwOne();
// This is now correct.
}
class ThrowsDemo {
}
static void throwOne() throws IllegalAccessException {
[Link]("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
[Link]("Caught " + e);
}
}
}
finally
• When exceptions are thrown, execution in a method takes a rather
abrupt, nonlinear path that alters the normal flow through the method.
• Depending upon how the method is coded, it is even possible for an
exception to cause the method to return prematurely.
• This could be a problem in some methods.
• For example, if a method opens a file upon entry and closes it upon
exit, then you will not want the code that closes the file to be bypassed
by the exception- handling mechanism.
• The finally keyword is designed to address this contingency.
finally
• The finally block contains code that always executes after a try/catch block completes,
and before control moves to the code following the try/catch.
• The finally block executes whether or not an exception is thrown.
• If an exception is thrown and no catch block matches, the finally block still executes.
• If a method is about to return (either due to an uncaught exception or an explicit return
statement inside try/catch), the finally block executes just before the method actually
returns.
• This makes finally useful for tasks like closing files, releasing resources, or cleaning up
before exiting a method.
• The finally block is optional, but every try must be followed by at least one catch or a
finally block.
// Execute a try block normally.
static void procC() {
// Demonstrate finally. try {
class FinallyDemo { [Link]("inside procC");
// Through an exception out of the method. } finally {
static void procA() { [Link]("procC's finally");
try { }
[Link]("inside procA"); }
throw new RuntimeException("demo"); public static void main(String args[]) {
} finally { try {
[Link]("procA's finally"); procA();
} } catch (Exception e) {
} [Link]("Exception caught");
// Return from within a try block. }
static void procB() { procB(); Output:
try { procC(); inside procA
[Link]("inside procB"); } procA’s finally
return; } Exception caught
} finally { inside procB
[Link]("procB's finally"); procB’s finally
} inside procC
} procC’s finally
Java’s Built-in Exceptions
• Inside the standard package [Link], Java defines several
exception classes.
• The unchecked exceptions defined in [Link] are Runtime
Exceptions.
Creating Own Exception Subclasses
User defined Exceptions
• Java’s built-in exceptions handle most common errors.
• To create own exception: just define a subclass of Exception (subclass of
Throwable).
• Subclasses don’t need to actually implement anything—it is their
existence in the type system that allows you to use them as exceptions.
• The Exception class does not define any methods of its own. It does, of
course, inherit those methods provided by Throwable.
• Thus, all exceptions, including those that you create, have the methods
defined by Throwable available to them.
• Exception defines four constructors.
1. Exception( )
2. Exception(String msg)
3. Exception(String msg, Throwable cause )
4. Exception(Throwable cause )

The last two were added by JDK 1.4 to support chained exceptions.
class MyException extends Exception {
private static final long serialVersionUID = 1L;
private int detail; OUTPUT
MyException(int a) { Called compute(1)
detail = a; Normal exit
} Called compute(20)
public String toString() { Caught MyException[20]
return "MyException[" + detail + "]";
}
}
class ExceptionDemo {
static void compute(int a) throws MyException {
[Link]("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
[Link]("Normal exit");
}
public static void main(String args[]) { try {
compute(1);
compute(20);
} catch (MyException e) {
[Link]("Caught " + e);}
}
}
// Example-2 A Class that represents use-defined expception
class MyException2 extends Exception
{
private static final long serialVersionUID = 1L;
public MyException2(String s)
{
super(s);
} OUTPUT
} Caught
public class NewDemo User defined exception…
{
// Driver Program
Public static void main(String args[])
{
try
{
throw new MyException2("User defined exception…");
}catch (MyException2 ex){
[Link]("Caught");
[Link]([Link]());
}
}
}

You might also like