does numberformatexception catch nullpointerexception? - exception

does try catch of NumberFormatException could handle NullPointerException? and does try catch of Exception could handle any type of exception?
try {
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

http://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html
Any sub-class of Exception you can see there is going to be catched by the try catch Exception.
NumberFormatException and NullpointerException are also Exception, but they're neither a sub-class of each other. That is, the first try-catch you stated won't catch a NullPointerException and vice-versa.

your syntax doesn't make sense, you can catch multiple exceptions, the most specific/narrow class of exception higher on the list:
try {
..code here...
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Related

Exception thrown from within orElseGet is wrapped with UndeclaredThrowableException

In one of our service classes, we are throwing an exception to deal with in the controller. However, in one of the cases, the exception is from within orElseGet.
def function() throws CustomException {
try {
ProjectAssignment assignment = workspaceRepositoryService.getWorkspaceMembership(command.assigneeEmail, workspaceId).map {
createOrUndelete(it, project, command.assigneeRole, createdBy)
}.orElseGet {
...
try {
Invitation invitation = workspaceService.inviteUserToWorkspace(command.assigneeEmail, workspace, createdBy) // throws CustomException
} catch (Exception e) {
throw e // getting CustomException
}
...
}
} catch(Exception e) {
throw e // getting UndeclaredThrowableException wrapping CustomException
}
}
The exception thrown inside orElseGet is wrapped with UndeclaredThrowableException. Is there a way to preserve the type of thrown exception?
...
catch( UndeclaredThrowableException e){
throw e.getCause()
}
catch(Exception e){
throw e
}

How to insert data into MySQL database by using the GWT, HTML and JDBC or Hibernate?

I am using the GWT(Google Web Tool-Kit) version 2.5.1. I am already done for develop sample application to display that username and password. But i am not identifying how to insert that values into MySQL database table by using JDBC of Hiberante. Any body know's that please send me complete code.
This is my mail-id:
subbareddyroyal#gmail.com
thanks & regards
Subbareddy.N
GWT is NOT a java application environment. It compiles to javascript. You must send your data to a java server running in a full JVM.
Here above i am posting the question.My self i a finding the answer to insert values into my sql database by using the jdbc, GWT,and HTML.
Here i am posting that what i am changing in my application.
you add the below insert in you impl class under the server folder in gwt application.
public void insert(String name) throws CommunicationsException {
try {
System.out.println("Before loading the driver class");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("after loading the driver ");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/gwt", "root", "root");
System.out.println("after creating the connection");
PreparedStatement ps = con
.prepareStatement("insert into gwt_user(userName)values(?)");
System.out.println("after loading the query");
ps.setString(1, name);
int i = ps.executeUpdate();
if (i < 0) {
return;
}
} catch (SQLException e) {
System.out.println(e);
}
}
after that you can add the below try catch block in ur greetserver(optional Name) method under the impl class.
try {
insert(name);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
then remaining all files are same.No need to change any file in your application

org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot get a connection, pool error Timeout waiting for idle object?

I am using liferay 6.1 and created my custom portlet and in that I am using custom query which directly get the records from database with the following ....
public List<DashBoardBean> GetPieChartDataForCampaignbyOrganization(
ThemeDisplay pThemeDisplay) {
log.info("In GetPieChartDataForCampaignbyOrganization ");
Context CtxObj;
long pParentOrgId;
ResultSet advResultSet = null;
List<DashBoardBean> dashboardbeanObjList = new ArrayList<DashBoardBean>();
try {
CtxObj = new InitialContext();
DataSource DsObj = (DataSource) CtxObj
.lookup("java:comp/env/jdbc/Liferay");
Connection ConObj = DsObj.getConnection();
Statement sStmtObj = ConObj.createStatement();
advResultSet = sStmtObj
.executeQuery("MY CUSTOM QUERY WILL BE HERE");
while (advResultSet.next()) {
DashBoardBean dashboardbeanObj = new DashBoardBean();
dashboardbeanObj
.setsOrganizationName(advResultSet.getString(1));
dashboardbeanObj.setlOrganizationCount(advResultSet.getLong(2));
dashboardbeanObjList.add(dashboardbeanObj);
}
} catch (NamingException e) {
// TODO Auto-generated catch block
dashboardbeanObjList = null;
e.printStackTrace();
} catch (SQLException e) {
dashboardbeanObjList = null;
// TODO Auto-generated catch block
e.printStackTrace();
} catch (PortalException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
log.info("Leave GetPieChartDataForCampaignbyOrganization ");
return dashboardbeanObjList;
}
Above is code snippet of one of my function... I have more then 5 function with the same structure... Just SQL query is different in function...
Now Problem is that I have to call more then 5 functions like this in page load...so when I use to reload the page frequently... It gives me error as following...
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot get a connection, pool error Timeout waiting for idle object
at org.apache.tomcat.dbcp.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:114)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
at emenu.advertise.appbl.DashBoardCustomQuery.GetPieChartDataForCampaignStatus(DashBoardCustomQuery.java:112)
at emenu.advertise.appbl.DashBordBL.GetPieChartDataForCampaignStatus(DashBordBL.java:292)
at emenu.advertise.portlet.RestaurantPortlet.serveResource(RestaurantPortlet.java:402)
at com.liferay.portlet.FilterChainImpl.doFilter(FilterChainImpl.java:118)
at com.liferay.portal.kernel.portlet.PortletFilterUtil.doFilter(PortletFilterUtil.java:71)
at com.liferay.portal.kernel.servlet.PortletServlet.service(PortletServlet.java:111)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:72)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilter.doFilter(InvokerFilter.java:73)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:471)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:402)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:329)
at com.liferay.portlet.InvokerPortletImpl.invoke(InvokerPortletImpl.java:531)
at com.liferay.portlet.InvokerPortletImpl.invokeResource(InvokerPortletImpl.java:626)
at com.liferay.portlet.InvokerPortletImpl.serveResource(InvokerPortletImpl.java:436)
at com.liferay.portal.action.LayoutAction.processPortletRequest(LayoutAction.java:1075)
at com.liferay.portal.action.LayoutAction.processLayout(LayoutAction.java:719)
at com.liferay.portal.action.LayoutAction.execute(LayoutAction.java:249)
at ............................
.......java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.util.NoSuchElementException: Timeout waiting for idle object
at org.apache.tomcat.dbcp.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:1171)
at org.apache.tomcat.dbcp.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:106)
... 131 more
09:24:11,163 INFO [http-bio-8080-exec-5][DashBoardCustomQuery:665] Leave GetHighestClickRestaurantName
09:24:11,163 INFO [http-bio-8080-exec-5][DashBoardCustomQuery:304] Leave GetLineChartDataForHighestClickedByRestaurant
09:24:11,164 INFO [http-bio-8080-exec-5][DashBordBL:166] Leave GetLineChartDataByRestaurant From DashBordBl
I know that I have done something wrong... But I don't know where... maybe it's because its SQL connection just lost from the server/// is it because I am not closing connection... Please help me... And correct me where am wrong... I had just given one example of my function the way I used to fetch data from other function...
i have just found the solution as i have never closed the connection object after execution of query.i have done as follows which works for me after try catch block...
finally {
try {
if(CtxObj!=null) {
CtxObj.close();
}
if(sStmtObj!=null){
sStmtObj.close();
}
if(ConObj!=null){
ConObj.close();
}
} catch (NamingException e) {
// TODO Auto-generated catch block
log.info(e);
} catch (SQLException e) {
// TODO Auto-generated catch block
log.info(e);
}
}

Embedding outofbox portlets in Custom portlet

I m trying to embed calender portlet in my custom portlet. But not able to accomplish this. I am getting below error:
javax.servlet.ServletException: javax.servlet.jsp.JspException:
ServletException in '/html/common/themes/portlet.jsp':
File "/html/common/themes/portlet.jsp" not found
at org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:911)
This is my class:
public class Hello extends MVCPortlet {
public void doView(RenderRequest request, RenderResponse response)
throws IOException, PortletException {
final String portletId = "47"; //hello world portlet id
final ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
HttpServletRequest req = PortalUtil.getHttpServletRequest(request);
HttpServletResponse res = (HttpServletResponse) request.getAttribute(PortletServlet.PORTLET_SERVLET_RESPONSE);
ServletContext servletContext = req.getSession().getServletContext();
PortletPreferences prefs = null;
try {
// get the portlet preferences
prefs = PortletPreferencesFactoryUtil.getPortletPreferences(req, portletId);
} catch (PortalException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("portlet preferences are " + prefs.toString());
//method 3
PortletPreferences originalPrefs = null;
try {
originalPrefs = PortletPreferencesFactoryUtil.getStrictLayoutPortletSetup(
themeDisplay.getLayout(), portletId);
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PortletPreferences targetPrefs = null;
try {
targetPrefs = PortletPreferencesFactoryUtil.getStrictLayoutPortletSetup(
themeDisplay.getLayout(), portletId);
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (java.util.Map.Entry<String, String[]> entry : targetPrefs.getMap().entrySet()) {
targetPrefs.reset(entry.getKey());
}
for (java.util.Map.Entry<String, String[]> entry : originalPrefs.getMap().entrySet()) {
targetPrefs.setValues(entry.getKey(), entry.getValue());
}
// Store preferencec.
targetPrefs.store();
try {
//finally render the portlet
final String portletHtml = RuntimePortletEmbedUtil.renderPortlet(request, response, portletId, "");
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Any insights to portlet embedding, I have already tried working on suggestions from this blog but no help.
Any suggestions or a way to accomplish this?
I guess there are issues to get the correct portlet preferences and authority to add a portlet over a targeted portlet.
Please update if you found some solutions to the problems.

exception handling and (throw ex)

What is the best way to handle an exception?
Also, why should I never write:
catch (Exception ex) { throw ex; }
The best way to handle an exception is to do something meaningful in the catch block (the one which in your example contains throw ex). The definition of "meaningful" completely depends on your needs.
You should not do catch (Exception ex) { throw ex; } because that brakes the exception chain. It is perfectly fine to catch an exception, handle it and re-throw so that the calling code can see it, but you should be doing so like this:
catch (Exception ex) { /* handling code; */ throw; }
Why would you catch the expection to just throw it again, if you were to catch the exception and do something other than just throw it, it would be fine!
try
{
}
catch(Exception ex)
{
// do something like log the exception
throw ex; // let another catch block handle the expection.
}