Class loader sub system: JVM’s class loader sub system performs 3 tasks a. It loads .class file into memory. b. It verifies byte code instructions. c. It allots memory required for the program.
Run time data area: This is the memory resource used by JVM and it is divided into 5 parts a. Method area: Method area stores class code and method code. (metaspace in Java SE 8) b. Heap: Objects are created on heap. c. Java stacks: Java stacks are the places where the Java methods are executed. A Java stack contains frames. On each frame, a separate method is executed. d. Program counter registers: The program counter registers store memory address of the instruction to be executed by the micro processor. e. Native method stacks: The native method stacks are places where native methods (for example, C language programs) are executed. Native method is a function, which is written in another language other than Java.
Native method interface: Native method interface is a program that connects native methods libraries (C header files) with JVM for executing native methods.
Native method library: holds the native libraries information.
Execution engine: Execution engine contains interpreter and JIT compiler, which converts byte code into machine code. JVM uses optimization technique(Hotspot Profiler) to decide which part to be interpreted and which part to be used with JIT compiler. The HotSpot represent the block of code(frequent) executed by JIT compiler.
Separation between Business. Logic (try block) & err handling logic(catch)
To recover from run time exceptions(to continue with execution flow)
Exception Handling flow and Hierarchy
Hierarchy:
Exception Class Methods
1. public void printStackTrace() — Displays name of exception class, reason, location dtls.
java.lang.ArithmeticException: / by zero
at DemoClass.calc(DemoClass.java:15)
at DemoClass.almostThere(DemoClass.java:9)
at DemoClass.main(DemoClass.java:5)
2. public String getMessage() — rets error mesg of exception
e.g. / by zero
3. public String toString() — rets Name of exc class & reason.
e.g. java.lang.ArithmeticException: / by zero
Following are Exceptions, root cause,origin time
Exception
Caused by
Discription
Thrown By(Type)
NullPointerException
String s = null; s.length();
Thrown when attempting to access an object
with a reference variable whose current value
is null.
By the JVM
ArithmeticException
int a = 3; int b=0; int q = a/b;
ArrayIndexOutOfBoundsException
int[] a = new int[10];
a[10];
Thrown when attempting to access an array
with an invalid index value (either negative
or beyond the length of the array).
By the JVM
ClassCastException
Object x =
new Integer(1);
String s = (String) x;
Thrown when attempting to cast a reference
variable to a type that fails the IS-A test.
By the JVM
StringIndexOutOfBoundsException
String s = “Hello”;
s.charAt(5);
IllegalArgumentException
(subclass of
java.lang.RunTimeException/unchecked)
Mysqroot(-5){
Throw new IAE(“msg”);}
Thrown when a method receives an argument
formatted differently than the method
expects.
Programmatically
IllegalStateException
Thrown when the state of the environment
doesn’t match the operation being attempted,
e.g., using a Scanner that’s been closed.
Programmatically
NumberFormatException
Thrown when a method that converts aString to a number
receives a String that itcannot convert.
Programmatically
StackOverflowError
Typically thrown when a method recurses
too deeply. (Each invocation is added to the
stack.)
By the JVM
NoClassDefFoundError
Thrown when the JVM can’t find a class it
needs, because of a command-line error, a
classpath issue, or a missing .class file
By the JVM
Where Exceptions Come From? Broad Categories Of Exception:-
JVM exceptions
Those exceptions or errors that are either exclusively or most logically thrown by the JVM.
Programmatic exceptions
Those exceptions that are thrown explicitly by application and/or API programmers.
Here are the steps that create a custom exception:
Create a new class whose name should end with an Exception, like the ClassNameException. This is a convention to differentiate an exception class from regular ones.
Make the class extends one of the exceptions that are subtypes of the java.lang.Exception class. Generally, a custom exception class always extends directly from the Exception class.
Create a constructor with a String parameter, which is the detail message of the exception. In this constructor, simply call the super constructor and pass the message, Best practice(Separation of Concern):Instead of passing ‘string as a parameter’ to super(), we can separate out error-codes and error-messages in separate enum .
Code Example: (ref.ACTS)
1. Create a package public class which extends Throwable (not recommended but legal)/Exception(recommended)/Error(not recommended but legal)/RuntimeExc (not recommended but legal)
public MyClassException extends Exception{ }
2.CustExc(String msg) : overload the constr : to invoke the super-class constr. of the form
Note:For details on working of Enun see post:”Anatomy of Enum”
Brief Conclusion:
Display of Custom Error Messages:
Error and exception messages that are expected to be displayed, in case of exception, are passed at time of throwing custom exception and in built-in case in-built messages are there.
Error Messages passed from throw clause can be retried in catch block either by calling method getMessage() of exception class or by calling getter method of Enum, which in turn in set in constructor of Custom Exception class.
Legal –throw new InvalidInputException(“invalid email”);
Final VS Finally
finally — keyword in exc handling finally — block — finally block ALWAYS survives(except System.exit(0)) i.e in the presence or absence of excs. 5.1 try{…} catch (Exception e){….} finally {….} 5.2 try{…} catch (NullPointerException e){….} finally {….} 5.3 try {…} finally {….}
Best Practices: extracts from Books
Effective Java: Bloach
Use checked exceptions for recoverable conditions
and runtime exceptions for programming errors:-
Description-
Some Rules from SCJP:-
It is illegal to use a try clause without either a catch clause or a finally clause. A try clause by itself will result in a compiler error. Any catch clauses mustimmediately follow the try block. Any finally clause must immediately follow the last catch clause (or it must immediately follow the try block if there is no catch). It is legal to omit either the catch clause or the finally clause, but not both
Exception, Error, RuntimeException, and Throwable types can all bethrown using the throw keyword, and can all be caught (although you rarely willcatch anything other than Exception subtypes).
You can keep throwing an exception down through the methods onthe stack. But what about when you get to the main() method at the bottom? You canthrow the exception out of main() as well. This results in the Java Virtual Machine (JVM)halting, and the stack trace will be printed to the output.
When an object of a subtype of Exception is thrown, it must be handledor declared. These objects are called checked exceptions, and include all exceptionsexcept those that are subtypes of RuntimeException, which are unchecked exceptions.