Right - with the 40, you'd probably want to unload the *uhem* 'magazine on a bear. The thing is, there are no guarantees. If, under duress, you can faithfully put rounds through about a 4" circle of a moving target, even 9mm would stop a bear with the right load.
BIG gun - BIG bullet - BIG damage. whilst ****ting a brick, I think i'd want a big bullet with the best chance of doing enough damage to convince a bear I'm not worth his/her trouble.
The Maasai (I believe) people of Eastern Africa have a right of passage into manhood of killing a lion. The approved technique is to arm one's self with a short throwing spear and finding a lion. When the lion attacks and jumps, the candidate throws the spear at the lion, aiming for one of two good sized 'soft spots' on either side of the lion equivalent of the sternum. If the throw is made properly, the spear injures the heart and kills the lion within a relatively short period of time. However, the candidate must perform the exercise exactly right.
In the same sense, a .40 S&W hollow point (or FMJ for penetration) round will kill a large, carnivorous, predatory bear. The candidate must perform the exercise exactly right. In either case, I'd prefer a Gatling gun in .45-70.
That always isn't an option, I'd still recommend something larger than a .40 S&W. I have no grudge against the round; I carry such a pistol for personal defense on a regular basis. But it's a bit light for large dangerous game. The smallest handgun I would suggest is a .44 Magnum, and even then the bear might fight you to a draw.
Were I going to be in 'bear country', I would take a short barreled 12 gauge shotgun loaded with slugs. It's not as convenient as a holstered handgun, but neither is being mauled or eaten.