0% found this document useful (0 votes)
24 views21 pages

Java Module 4 CH Pater 10

Here is a Java program to raise a custom exception for the DivisionByZero scenario using try, catch, throw and finally: class DivisionByZeroException extends Exception { public DivisionByZeroException(String s) { super(s); } } class ExceptionDemo { public static void compute(int a, int b) throws DivisionByZeroException { if(b == 0) { throw new DivisionByZeroException("Attempted to divide by zero"); } int result = a/b; System.out.println("Result: " + result); } public static void main(String args[]) { try { compute(10, 0); } catch

Uploaded by

2022becs190
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)
24 views21 pages

Java Module 4 CH Pater 10

Here is a Java program to raise a custom exception for the DivisionByZero scenario using try, catch, throw and finally: class DivisionByZeroException extends Exception { public DivisionByZeroException(String s) { super(s); } } class ExceptionDemo { public static void compute(int a, int b) throws DivisionByZeroException { if(b == 0) { throw new DivisionByZeroException("Attempted to divide by zero"); } int result = a/b; System.out.println("Result: " + result); } public static void main(String args[]) { try { compute(10, 0); } catch

Uploaded by

2022becs190
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
You are on page 1/ 21

Exceptions

● abnormal condition that arises in the code at run-time.


●Java exception handling is managed via five
keywords: try, catch, throw, throws, and finally
● The built-in class provided by the JRE is Throwable
class Exception {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}

java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
try: A suspected code segment is kept inside the try block.

catch: The remedy is written within catch block.

throw: Whenever a run-time error occurs, the code should throw


an exception.

throws: If a method cannot handle the exception on its own but


some subsequent method can handle it, then the first method
re-throws (passes on) the same exception.

finally: the block should contain the code to be executed after


finishing try-block.
try {
// block of code which monitors for errors
}
catch (ExceptionType1 exceptionObject1) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exceptionObject2) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
}
Types of Exception
● Checked, unchecked, and error
●Checked: The classes that directly inherit the Throwable class except
RuntimeException and Error are known as checked exceptions. Eg., IOException,
SQLException, etc., Such exceptions are checked at compile-time. You can recover from
them in most cases.
●Unchecked: e.g., ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc., are unchecked exceptions meaning they are
not checked at compile-time, but checked at runtime by the Java Virtual Machine.
●Error: irrecoverable. Some e.g., OutOfMemoryError, VirtualMachineError,
AssertionError, etc.
class Exception2 {
try and catch
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.");
}
}
Multiple catch blocks
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.");
}
}
Order of exception handling
It is important to remember that exception subclasses
must come before any of their superclasses. This is
because a catch statement that uses a superclass will
catch exceptions of that type plus any of its subclasses.
class NestedTry {
Nested try statement
public static void main(String args[]) {
try {
int a = args.length;
int b = 42 / a;
try {
if( a == 1) {
int c[] = { 1 };
c[42] = 99;
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
throw
● Syntax: throw ThrowableInstance;
● throw: Keyword
●ThrowableInstance: Object of Throwable class or
subclass.
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demo");
throw e; // rethrows the exception
}
}

public static void main(String args[]) {


try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}
throws
● A throws clause lists the types of exceptions that a method might throw.
type method-name(parameter-list) throws exception-list {
// body of method
}
●exception-list is a comma-separated list of the exceptions that a method can
throw.
class ThrowsDemo {
static void throwOne() {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}

public static void main(String args[]) {


throwOne();
}
}
● First, you need to declare that throwOne( ) throws IllegalAccessException.
Second, main( ) must define a try/catch statement that catches this exception.

● If you run the above code, you will get the following error:
ThrowsDemo.java:8: error: unreported exception IllegalAccessException; must
be caught or declared to be thrown
throw new IllegalAccessException("demo");
^
1 error
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
finally
●finally creates a block of code that will be executed
after a try/catch block has been completed and before
the code following the try/catch block.
try {

int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[10]);

catch (Exception e) {

System.out.println("Something went wrong.");

finally {

System.out.println("The 'try catch' is finished.");

}
●Chained Exception helps to identify a situation in
which one exception causes another Exception in an
application. For instance, consider a method that
throws an ArithmeticException because of an attempt
to divide by zero but the actual cause of exception was
an I/O error which caused the divisor to be zero.
Lab Activity/Exercise 22
Develop a JAVA program to raise a custom exception
(also called a user-defined exception) for the
DivisionByZero scenario, using try, catch, throw, and
finally.

You might also like